package com.njcn.msgpush.module.push.client;

import com.njcn.msgpush.module.push.client.factory.MessageProviderFactory;
import com.njcn.msgpush.module.push.client.factory.impl.AliyunProviderFactory;
import com.njcn.msgpush.module.push.client.factory.impl.TelecomProviderFactory;
import com.njcn.msgpush.module.push.client.factory.impl.UniPushProviderFactory;
import com.njcn.msgpush.module.push.dal.dataobject.channel.ChannelProviderConfigDO;
import com.njcn.msgpush.module.push.enums.ProviderTypeEnum;
import com.njcn.msgpush.module.push.service.channel.ChannelProviderConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

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

/**
 * @author caozehui
 * @data 2026-02-10
 */
@Configuration
public class ClientConfiguration {

    @Autowired
    private ChannelProviderConfigService channelProviderConfigService;

    @Bean
    public Map<String, MessageProviderFactory> messageProviderFactoryMap() throws Exception {
        List<ChannelProviderConfigDO> activeProviders = channelProviderConfigService.getActiveProviders();
        Map<String, MessageProviderFactory> messageProviderFactoryMap = new HashMap<>();

        for (ChannelProviderConfigDO config : activeProviders) {
            switch (ProviderTypeEnum.getByCode(config.getProviderType())) {
                case ALIYUN: {
                    MessageProviderFactory orDefault = messageProviderFactoryMap.getOrDefault(ProviderTypeEnum.ALIYUN.getCode(), new AliyunProviderFactory());
                    messageProviderFactoryMap.put(ProviderTypeEnum.ALIYUN.getCode(), orDefault);
                }
                break;
                case TELECOM: {
                    MessageProviderFactory orDefault = messageProviderFactoryMap.getOrDefault(ProviderTypeEnum.TELECOM.getCode(), new TelecomProviderFactory());
                    messageProviderFactoryMap.put(ProviderTypeEnum.TELECOM.getCode(), orDefault);
                }
                break;
                case UNIPUSH: {
                    MessageProviderFactory orDefault = messageProviderFactoryMap.getOrDefault(ProviderTypeEnum.UNIPUSH.getCode(), new UniPushProviderFactory());
                    messageProviderFactoryMap.put(ProviderTypeEnum.UNIPUSH.getCode(), orDefault);
                }
                break;
                default:
                    throw new IllegalArgumentException("该" + config.getProviderType() + "服务商暂不支持");
            }
        }

        if (messageProviderFactoryMap.isEmpty()) {
            throw new Exception("当前没有激活的渠道服务商!");
        }
        return messageProviderFactoryMap;
    }
}
