package org.dromara.pay.core;

import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.pay.enums.PayChannelEnum;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 支付策略工厂
 *
 * @author pengles
 */
@Slf4j
@Component
public class PayStrategyFactory {

    private final Map<String, PayStrategy> strategyMap = new ConcurrentHashMap<>();

    /**
     * 注册策略
     */
    public void register(String channelCode, PayStrategy strategy) {
        strategyMap.put(channelCode, strategy);
    }

    /**
     * 获取策略
     */
    public PayStrategy getStrategy(String channelCode) {
        PayChannelEnum channelEnum = PayChannelEnum.getByCode(channelCode);
        if (channelEnum == null) {
            throw new ServiceException("不支持的支付渠道: " + channelCode);
        }
        // 简单映射：假设 code 前缀决定策略，例如 wx_pub -> WechatPayStrategy
        // 或者直接根据 code 获取 bean
        // 这里为了简单，假设实现类自己注册，或者通过 BeanName 获取
        // 比如 WechatPayStrategy 处理所有 wx_ 开头的
        
        // 更好的方式是策略实现类在 init 时注册自己
        PayStrategy strategy = strategyMap.get(channelCode);
        if (strategy == null) {
            // 尝试根据前缀查找 (例如 wx_pub, wx_lite 都用 WechatPayStrategy)
             if (channelCode.startsWith("wx_")) {
                 strategy = strategyMap.get("wx");
             } else if (channelCode.startsWith("alipay_")) {
                 strategy = strategyMap.get("alipay");
             }
        }
        
        if (strategy == null) {
             throw new ServiceException("未找到支付策略: " + channelCode);
        }
        return strategy;
    }
}
