package com.fs.newAdv.integration.factory;


import com.fs.newAdv.enums.AdvertiserTypeEnum;
import com.fs.newAdv.integration.adapter.IAdvertiserAdapter;
import com.fs.newAdv.integration.client.IApiClient;
import com.fs.common.exception.base.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 广告商处理器工厂（工厂模式）
 * 根据广告商类型获取对应的适配器和策略
 *
 * @author zhangqin
 * @date 2025-11-03
 */
@Slf4j
@Component
public class AdvertiserHandlerFactory {

    @Autowired
    private List<IAdvertiserAdapter> advertiserAdapters;
    @Autowired
    private List<IApiClient> apiClients;

    /**
     * 适配器缓存
     */
    private final Map<AdvertiserTypeEnum, IAdvertiserAdapter> adapterMap = new ConcurrentHashMap<>();
    /**
     * 客户端
     */
    private final Map<AdvertiserTypeEnum, IApiClient> apiClientMap = new ConcurrentHashMap<>();

    /**
     * 初始化工厂
     */
    @PostConstruct
    public void init() {
        // 初始化适配器Map
        for (IAdvertiserAdapter adapter : advertiserAdapters) {
            adapterMap.put(adapter.getAdvertiserType(), adapter);
        }
        // 初始化策略Map
        for (IApiClient apiClient : apiClients) {
            apiClientMap.put(apiClient.getAdvertiserType(), apiClient);
        }
        log.info("广告商处理器工厂初始化完成，适配器数量：{}，客户端：{}",
                adapterMap.size(), apiClientMap.size());
    }

    /**
     * 获取适配器
     *
     * @param advertiserType 广告商类型
     * @return 适配器
     */
    public IAdvertiserAdapter getAdapter(AdvertiserTypeEnum advertiserType) {
        IAdvertiserAdapter adapter = adapterMap.get(advertiserType);
        if (adapter == null) {
            throw new BusinessException("不支持的广告商类型：" + advertiserType);
        }
        return adapter;
    }

    /**
     * 获取回调策略
     *
     * @param advertiserType 广告商类型
     * @return 回调策略
     */
    public IApiClient getApiClient(AdvertiserTypeEnum advertiserType) {
        IApiClient apiClient = apiClientMap.get(advertiserType);
        if (apiClient == null) {
            throw new BusinessException("不支持的广告商类型：" + advertiserType);
        }
        return apiClient;
    }
}

