package com.red.circle.order.app.service;

import com.red.circle.component.pay.paymax.PayMaxUtils;
import com.red.circle.order.app.common.MiFaPayPlaceAnOrderParam;
import com.red.circle.order.app.dto.clientobject.MiFaPayResponseCO;
import com.red.circle.order.infra.config.MiFaPayProperties;
import com.red.circle.tool.core.http.RcHttpClient;
import com.red.circle.tool.core.json.JacksonUtils;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * MiFaPay支付服务
 *
 * @author system
 */
@Slf4j
@Service
public class MiFaPayService {

    /**
     * 下单接口路径
     */
    public static final String NOTIFY_URL = "";
    private static final String PLACE_ORDER_PATH = "/paygateway/mbpay/order/en_v2";

    private final String active;
    private final MiFaPayProperties miFaPayProperties;
    private final RcHttpClient rcHttpClient = RcHttpClient.builder().build();

    public MiFaPayService(@Value("${spring.profiles.active:dev}") String active,
                          MiFaPayProperties miFaPayProperties) {
        this.active = active;
        this.miFaPayProperties = miFaPayProperties;
    }

    /**
     * 发起支付下单
     *
     * @param param 下单参数
     * @return 支付响应
     */
    public MiFaPayResponseCO placeAnOrder(MiFaPayPlaceAnOrderParam param) {
        // 设置商户编号
        param.setMerNo(miFaPayProperties.getMerNo());

        String url = miFaPayProperties.getGatewayBaseUrl() + PLACE_ORDER_PATH;
        
        // 将param转为JSON字符串作为data
        String dataJson = JacksonUtils.toJson(param);
        
        // 对data进行签名
        String sign = PayMaxUtils.signRsa(dataJson, miFaPayProperties.getRsaPrivateKey());

        // 构建请求体：merAccount + sign + data
        MiFaPayRequest request = new MiFaPayRequest();
        request.setMerAccount(miFaPayProperties.getMerAccount());
        request.setSign(sign);
        request.setData(dataJson);

        String body = JacksonUtils.toJson(request);

        // 非生产环境打印日志
        if (!Objects.equals(active, "prod")) {
            log.warn("MiFaPay Request URL: {}\nBody:{}", url, body);
        }

        MiFaPayResponseCO response = rcHttpClient.post()
                .uri(url)
                .contentType("application/json")
                .bodyValue(body)
                .retrieve()
                .bodyToEntity(MiFaPayResponseCO.class)
                .block();

        // 非生产环境打印响应日志
        if (!Objects.equals(active, "prod")) {
            log.warn("MiFaPay Response: {}", JacksonUtils.toJson(response));
        }

        // 验证响应签名
        if (response != null && response.isSuccess() && response.getData() != null) {
//            boolean validSign = PayMaxUtils.validSignRsa(
//                    response.getData(),
//                    response.getSign(),
//                    miFaPayProperties.getPlatformRsaPublicKey()
//            );
//            if (!validSign) {
//                log.error("MiFaPay response sign verification failed!");
//            }
        }

        return response;
    }

    /**
     * MiFaPay请求体结构
     */
    @Data
    public static class MiFaPayRequest {
        /**
         * 商户标识
         */
        private String merAccount;

        /**
         * 签名
         */
        private String sign;

        /**
         * 主请求参数（JSON字符串）
         */
        private String data;
    }
}
