package com.ycwl.basic.order.factory;

import com.ycwl.basic.order.strategy.IDuplicatePurchaseChecker;
import com.ycwl.basic.product.capability.DuplicateCheckStrategy;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 重复购买检查策略工厂
 *
 * 设计原则：
 * 1. 自动注册：Spring 自动注入所有策略实现并注册
 * 2. 类型安全：根据枚举类型查找策略
 * 3. 失败快速：找不到策略时抛出异常
 */
@Lazy
@Slf4j
@Service
public class DuplicatePurchaseCheckerFactory {

    private final Map<DuplicateCheckStrategy, IDuplicatePurchaseChecker> checkerMap = new HashMap<>();

    /**
     * 构造函数：自动注册所有策略实现
     */
    @Autowired
    public DuplicatePurchaseCheckerFactory(List<IDuplicatePurchaseChecker> checkers) {
        for (IDuplicatePurchaseChecker checker : checkers) {
            DuplicateCheckStrategy strategy = checker.getStrategyType();
            checkerMap.put(strategy, checker);
            log.info("注册重复购买检查策略: {} -> {}", strategy, checker.getClass().getSimpleName());
        }
        log.info("重复购买检查策略工厂初始化完成，共注册 {} 个策略", checkerMap.size());
    }

    /**
     * 根据策略类型获取检查器
     *
     * @param strategy 策略类型
     * @return 对应的检查器实现
     * @throws IllegalArgumentException 如果找不到对应的策略实现
     */
    public IDuplicatePurchaseChecker getChecker(DuplicateCheckStrategy strategy) {
        IDuplicatePurchaseChecker checker = checkerMap.get(strategy);
        if (checker == null) {
            throw new IllegalArgumentException("未找到重复购买检查策略: " + strategy);
        }
        return checker;
    }

    /**
     * 检查是否支持指定策略
     */
    public boolean supportsStrategy(DuplicateCheckStrategy strategy) {
        return checkerMap.containsKey(strategy);
    }

    /**
     * 获取所有已注册的策略类型
     */
    public Map<DuplicateCheckStrategy, IDuplicatePurchaseChecker> getAllCheckers() {
        return new HashMap<>(checkerMap);
    }
}
