package com.haha.service.payment;

import com.haha.common.enums.PaymentChannel;
import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.EnumMap;
import java.util.List;
import java.util.Map;

/**
 * 支付渠道工厂类
 * 负责管理和分发支付策略
 */
@Slf4j
@Component
public class PaymentChannelFactory {
    
    @Autowired
    private List<PaymentStrategy> strategies;
    
    private final Map<PaymentChannel, PaymentStrategy> strategyMap = new EnumMap<>(PaymentChannel.class);
    
    /**
     * 初始化：注册所有支付策略
     */
    @PostConstruct
    public void init() {
        for (PaymentStrategy strategy : strategies) {
            strategyMap.put(strategy.getChannel(), strategy);
            log.info("注册支付策略: {} -> {}", strategy.getChannel().getCode(), strategy.getClass().getSimpleName());
        }
    }
    
    /**
     * 获取指定渠道的支付策略
     * @param channel 支付渠道
     * @return 支付策略实例
     * @throws IllegalArgumentException 如果渠道不支持
     */
    public PaymentStrategy getStrategy(PaymentChannel channel) {
        PaymentStrategy strategy = strategyMap.get(channel);
        if (strategy == null) {
            throw new IllegalArgumentException("不支持的支付渠道: " + channel.getCode());
        }
        return strategy;
    }
    
    /**
     * 获取所有已注册的支付渠道
     * @return 已注册的支付渠道列表
     */
    public List<PaymentChannel> getAvailableChannels() {
        return List.copyOf(strategyMap.keySet());
    }
    
    /**
     * 判断是否支持某个渠道
     * @param channel 支付渠道
     * @return 是否支持
     */
    public boolean isChannelSupported(PaymentChannel channel) {
        return strategyMap.containsKey(channel);
    }
}
