package com.jeesharp.business.modules.pay.listener.upevent;

import com.jeesharp.business.modules.pay.dto.BasicPayOrderData;
import com.jeesharp.business.modules.pay.dto.PayWechatPrepayRouteSnapshotDTO;
import com.jeesharp.business.modules.pay.paywechatconfig.service.PayWechatConfigService;
import com.jeesharp.business.modules.pay.paywechatconfig.service.PayWechatPublicConfigSupport;
import com.jeesharp.business.modules.pay.service.weixin.PayWechatJsapiPrepayService;
import com.jeesharp.business.modules.pay.service.weixin.PayWechatV3NotificationService;
import com.jeesharp.business.modules.pay.vo.PayWechatPublicConfigVO;
import com.jeesharp.business.modules.pay.vo.WechatJsapiPrepayVO;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * {@link com.jeesharp.business.modules.pay.api.PayCenterApi} 实现：微信 JSAPI 预支付与回调解析。
 *
 * @author jeesharp
 * @since 2026-05-25
 */
@Service
@RequiredArgsConstructor
public class PayCenterServiceImpl implements PayOrderService {

    private final PayWechatJsapiPrepayService payWechatJsapiPrepayService;
    private final PayWechatConfigService payWechatConfigService;
    private final PayWechatPublicConfigSupport payWechatPublicConfigSupport;
    private final PayWechatV3NotificationService payWechatV3NotificationService;

    @Override
    public PayWechatPublicConfigVO getWechatPublicConfig() {
        return getWechatPublicConfig(null);
    }

    @Override
    public PayWechatPublicConfigVO getWechatPublicConfig(String tenantId) {
        return payWechatPublicConfigSupport.build(payWechatConfigService.findActive(tenantId));
    }

    @Override
    public Map<String, Object> wechatParsePayNotify(String rawBody, Map<String, String> headers) {
        return wechatParsePayNotify(rawBody, headers, null);
    }

    public Map<String, Object> wechatParsePayNotify(String rawBody, Map<String, String> headers, String tenantId) {
        try {
            return payWechatV3NotificationService.parseNotification(rawBody, headers, tenantId);
        } catch (RuntimeException e) {
            throw e;
        } catch (Exception e) {
            throw new IllegalStateException("微信支付回调解析失败: " + e.getMessage(), e);
        }
    }

    @Override
    public WechatJsapiPrepayVO wechatJsapiPrepay(BasicPayOrderData payOrderData) {
        try {
            return payWechatJsapiPrepayService.prepay(payOrderData);
        } catch (RuntimeException e) {
            throw e;
        } catch (Exception e) {
            throw new IllegalStateException("微信 JSAPI 预支付失败: " + e.getMessage(), e);
        }
    }

    @Override
    public PayWechatPrepayRouteSnapshotDTO previewWechatJsapiRoute(BasicPayOrderData payOrderData) {
        return payWechatJsapiPrepayService.previewRoute(payOrderData);
    }
}
