package com.jeesharp.business.modules.pay.paypufaconfig.config;

import cn.hutool.core.util.StrUtil;
import com.jeesharp.business.modules.pay.paypufaconfig.entity.PayPufaConfig;
import com.jeesharp.business.modules.pay.paypufaconfig.service.PayPufaConfigService;
import com.jeesharp.business.modules.pay.paypufaconfig.support.PayPufaCredentialSupport;
import com.jeesharp.business.modules.pay.paytype.pufapay.config.PuFaPayConfig;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

/**
 * 按租户解析 {@code pay_pufa_config} 并写入 {@link PuFaPayConfig} 静态字段供 legacy 浦发 SDK 使用。
 *
 * @author jeesharp
 * @since 2026-05-25
 */
@Component
@RequiredArgsConstructor
public class PayPufaConfigHolder {

    private final PayPufaConfigService payPufaConfigService;

    public PayPufaConfig findActiveConfig(String tenantId) {
        return payPufaConfigService.findActive(tenantId);
    }

    public PayPufaConfig requireActiveConfig(String tenantId) {
        PayPufaConfig config = findActiveConfig(tenantId);
        if (config == null) {
            throw new IllegalStateException("未配置浦发支付：请在管理后台【支付 · 浦发配置】保存并启用");
        }
        return config;
    }

    public void applyRuntime(String tenantId) {
        PayPufaConfig config = findActiveConfig(tenantId);
        if (config != null) {
            applyFromConfig(config);
        }
    }

    public void applyFromConfig(PayPufaConfig config) {
        if (config == null) {
            return;
        }
        PuFaPayConfig.applyFrom(config, resolveNotifyUrl(config));
    }

    public void requirePfaEnabled(String tenantId) {
        PayPufaConfig config = requireActiveConfig(tenantId);
        if (!PayPufaCredentialSupport.isPfaEnabled(config)) {
            throw new IllegalStateException("未启用真实浦发下单");
        }
    }

    public String resolveNotifyUrl(PayPufaConfig config) {
        if (config == null) {
            return PuFaPayConfig.NOTIFY_URL;
        }
        String base = StrUtil.blankToDefault(config.getNotifyBaseUrl(), "");
        String path = StrUtil.blankToDefault(config.getPayCenterNotifyPath(), "/api/pay/payNotify/pfNotify");
        if (base.isEmpty()) {
            return path.startsWith("http") ? path : PuFaPayConfig.NOTIFY_URL;
        }
        return base.replaceAll("/+$", "") + (path.startsWith("/") ? path : "/" + path);
    }
}
