package com.jeesharp.business.modules.pay.paytype.alipay.config;

import cn.hutool.core.util.StrUtil;
import com.alipay.api.AlipayApiException;
import com.jeesharp.business.modules.pay.payalipayconfig.entity.PayAlipayConfig;
import com.jeesharp.business.modules.pay.payalipayconfig.service.PayAlipayConfigService;
import com.jeesharp.business.modules.pay.paytype.alipay.AliPayApiConfig;
import com.jeesharp.business.modules.pay.paytype.alipay.AliPayApiConfigKit;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import jakarta.annotation.PostConstruct;

/**
 * 启动时将 {@link AliPayChannelProperties} 写入 {@link AliPayApiConfigKit}，供 legacy 支付宝策略使用。
 *
 * @author jeesharp
 * @since 2026-05-25
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class AliPayChannelBootstrap {

    private final AliPayChannelProperties properties;
    private final PayAlipayConfigService payAlipayConfigService;

    @PostConstruct
    public void init() {
        PayAlipayConfig db = payAlipayConfigService.findActive(null);
        if (db != null) {
            log.info("支付宝渠道已存在库表配置，跳过 YAML 占位初始化（tenant=平台）");
            return;
        }
        try {
            AliPayApiConfig config = AliPayApiConfig.builder()
                    .setAppId(properties.getAppId())
                    .setPrivateKey(properties.getPrivateKey())
                    .setAliPayPublicKey(properties.getAliPayPublicKey())
                    .setServiceUrl(StrUtil.blankToDefault(properties.getServiceUrl(),
                            "https://openapi.alipay.com/gateway.do"))
                    .setCharset(properties.getCharset())
                    .setSignType(properties.getSignType())
                    .setCertModel(properties.isCertModel());
            if (properties.isCertModel()) {
                config.setAppCertPath(properties.getAppCertPath())
                        .setAliPayCertPath(properties.getAliPayCertPath())
                        .setAliPayRootCertPath(properties.getAliPayRootCertPath())
                        .buildByCert();
            } else {
                config.build();
            }
            AliPayApiConfigKit.putApiConfig(config);
            if (properties.isEnabled()) {
                log.info("支付宝渠道已启用（YAML ali.pay），notifyUrl={}", properties.getNotifyUrl());
            } else {
                log.info("支付宝渠道占位配置已加载（ali.pay.enabled=false），notifyUrl={}", properties.getNotifyUrl());
            }
        } catch (AlipayApiException e) {
            throw new IllegalStateException("支付宝 SDK 配置初始化失败: " + e.getMessage(), e);
        }
    }
}
