package com.red.circle.order.app.command.pay.web;

import com.red.circle.component.pay.paymax.PayMaxUtils;
import com.red.circle.order.app.common.InAppPurchaseCommon;
import com.red.circle.order.domain.order.MiFaPayReceivePaymentNotice;
import com.red.circle.order.infra.config.MiFaPayProperties;
import com.red.circle.order.infra.database.mongo.order.InAppPurchaseCollectionReceiptService;
import com.red.circle.order.infra.database.mongo.order.InAppPurchaseDetailsService;
import com.red.circle.order.infra.database.mongo.order.entity.InAppPurchaseDetails;
import com.red.circle.order.infra.database.mongo.order.entity.assist.InAppPurchaseEventNotice;
import com.red.circle.order.inner.model.enums.inapp.InAppPurchaseStatus;
import com.red.circle.tool.core.date.TimestampUtils;
import com.red.circle.tool.core.text.StringUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.util.Objects;

/**
 * MiFaPay 支付回调通知处理
 *
 * @author system
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class MiFaPayServerNoticeReceivePaymentCmdExe {

    private static final String SUCCESS = "SUCCESS";
    private static final String FAIL = "FAIL";

    private final MiFaPayProperties miFaPayProperties;
    private final InAppPurchaseCommon inAppPurchaseCommon;
    private final InAppPurchaseDetailsService inAppPurchaseDetailsService;
    private final InAppPurchaseCollectionReceiptService inAppPurchaseCollectionReceiptService;

    /**
     * 处理MiFaPay支付回调
     *
     * @param body 请求体
     * @return SUCCESS 或 FAIL
     */
    public String execute(byte[] body) {
        //  参数校验
        if (Objects.isNull(body) || body.length == 0) {
            log.error("MiFaPay回调参数为空");
            return FAIL;
        }

        String bodyParam = new String(body, StandardCharsets.UTF_8);
        log.warn("MiFaPay回调通知: body={}", bodyParam);

        //  解析回调数据
        MiFaPayReceivePaymentNotice notice = MiFaPayReceivePaymentNotice.serializable(bodyParam);
        if (Objects.isNull(notice) || Objects.isNull(notice.getNoticeData())) {
            log.error("MiFaPay回调数据解析失败: {}", bodyParam);
            return FAIL;
        }

        //  验证签名（对data字段验签）
        if (StringUtils.isBlank(notice.getSign()) || StringUtils.isBlank(notice.getData())) {
            log.error("MiFaPay回调签名或data为空");
            return FAIL;
        }

        boolean validSign = PayMaxUtils.validSignRsa(
                notice.getData(),
                notice.getSign(),
                miFaPayProperties.getPlatformRsaPublicKey()
        );

        if (!validSign) {
            log.error("MiFaPay回调验签失败: sign={}, data={}", notice.getSign(), notice.getData());
            return FAIL;
        }

        MiFaPayReceivePaymentNotice.MiFaPayNoticeData noticeData = notice.getNoticeData();

        //  查询订单
        InAppPurchaseDetails order = inAppPurchaseDetailsService.getById(noticeData.getOrderId());
        if (Objects.isNull(order)) {
            log.error("MiFaPay回调未找到订单: orderId={}", noticeData.getOrderId());
            return FAIL;
        }

        //  检查订单状态，避免重复处理
        if (!Objects.equals(order.getStatus(), InAppPurchaseStatus.CREATE)) {
            log.warn("MiFaPay订单已处理: orderId={}, status={}", order.getId(), order.getStatus());
            return SUCCESS;
        }

        //  记录回调通知
        inAppPurchaseDetailsService.addPayNotices(order.getId(),
                new InAppPurchaseEventNotice()
                        .setEventId(notice.getSign())
                        .setNoticeType("mifapay-" + noticeData.getOrderStatus())
                        .setNoticeData(notice)
                        .setCreateTime(TimestampUtils.now())
        );

        //  处理支付成功
        if (noticeData.isSuccess()) {
            if (!Objects.equals(order.statusEqCreate(), Boolean.TRUE)) {
                log.warn("MiFaPay订单状态不是CREATE: orderId={}", order.getId());
                return SUCCESS;
            }

            // 收款单
            if (order.receiptTypeEqReceipt()) {
                inAppPurchaseCommon.inAppPurchaseReceipt(order);
                log.info("MiFaPay收款单处理成功: orderId={}", order.getId());
                return SUCCESS;
            }

            // 付款单
            if (order.receiptTypeEqPayment()) {
                inAppPurchaseCommon.inAppPurchasePayment(order);
                log.info("MiFaPay付款单处理成功: orderId={}", order.getId());
                return SUCCESS;
            }

            log.error("MiFaPay订单类型错误: orderId={}", order.getId());
            return FAIL;
        }

        //  处理支付失败
        if (noticeData.isFailed()) {
            if (order.receiptTypeEqReceipt()) {
                inAppPurchaseCollectionReceiptService.updateStatusSuccessFail(order.getId());
            }
            inAppPurchaseDetailsService.updateStatusReason(
                    order.getId(),
                    InAppPurchaseStatus.FAIL,
                    String.format("MiFaPay支付失败: %s", noticeData.getOrderStatus())
            );
            log.info("MiFaPay支付失败处理完成: orderId={}", order.getId());
            return SUCCESS;
        }

        log.error("MiFaPay未知订单状态: orderId={}, status={}", order.getId(), noticeData.getOrderStatus());
        return SUCCESS;
    }
}
