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

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.njcn.msgpush.module.push.client.factory.MessageProviderFactory;
import com.njcn.msgpush.module.push.client.factory.ProviderFactorySupport;
import com.njcn.msgpush.module.push.client.sender.AppPushSender;
import com.njcn.msgpush.module.push.client.sender.EmailSender;
import com.njcn.msgpush.module.push.client.sender.SendOutcome;
import com.njcn.msgpush.module.push.client.sender.Sender;
import com.njcn.msgpush.module.push.client.sender.SmsSender;
import com.njcn.msgpush.module.push.client.sender.fallback.FixedResultAppPushSender;
import com.njcn.msgpush.module.push.client.sender.fallback.FixedResultEmailSender;
import com.njcn.msgpush.module.push.client.sender.fallback.FixedResultSmsSender;
import com.njcn.msgpush.module.push.client.sender.impl.apppush.UniPushAppPushSender;
import com.njcn.msgpush.module.push.client.setting.impl.UniPushAppPushSetting;
import com.njcn.msgpush.module.push.dal.dataobject.channel.ChannelProviderConfigDO;

public class UniPushProviderFactory implements MessageProviderFactory {

    private static final String APP_ID = "appId";
    private static final String MASTER_SECRET = "masterSecret";

    @Override
    public SmsSender createSmsSender(ChannelProviderConfigDO config, Sender sender) {
        // 当前服务商没有该能力时，返回固定结果 sender，避免主流程处理 null。
        return new FixedResultSmsSender(SendOutcome.UNSUPPORTED_CHANNEL, "当前服务商不支持短信发送");
    }

    @Override
    public EmailSender createEmailSender(ChannelProviderConfigDO config, Sender sender) {
        // 当前服务商没有该能力时，返回固定结果 sender，避免主流程处理 null。
        return new FixedResultEmailSender(SendOutcome.UNSUPPORTED_CHANNEL, "当前服务商不支持邮件发送");
    }

    @Override
    public AppPushSender createAppPushSender(ChannelProviderConfigDO config, Sender sender) {
        JSONObject extraConfig = StrUtil.isBlank(config.getExtraConfig()) ? new JSONObject() : JSON.parseObject(config.getExtraConfig());
        String appId = extraConfig.getString(APP_ID);
        String masterSecret = extraConfig.getString(MASTER_SECRET);
        // 配置缺失时返回固定结果 sender，由主流程统一落库为配置异常。
        if (ProviderFactorySupport.hasBlank(appId, config.getAppKey(), config.getAppSecret(), masterSecret)) {
            return new FixedResultAppPushSender(SendOutcome.CONFIG_INVALID, "当前服务商 APP 推送渠道配置不完整");
        }
        UniPushAppPushSetting uniPushAppPushSetting = new UniPushAppPushSetting(
                appId,
                config.getAppKey(),
                config.getAppSecret(),
                masterSecret
        );
        return new UniPushAppPushSender(uniPushAppPushSetting, sender);
    }
}
