package impl

import (
	"net/smtp"
	"strings"

	"bsm/full/module/base/sender/internal/config"
	AliYunClient "github.com/alibabacloud-go/darabonba-openapi/v2/client"
	dysmsapi "github.com/alibabacloud-go/dysmsapi-20180501/v2/client"
	"github.com/aliyun/credentials-go/credentials"
	"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common"
	"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common/profile"
	TencentCloud "github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/sms/v20210111"
)

var (
	Provider *ProviderClient
)

type ProviderClient struct {
	Aliyun  *dysmsapi.Client
	Google  *smtp.Client
	QQ      *smtp.Client
	Tencent *TencentCloud.Client
}

func (p *ProviderClient) init() {
	Provider = &ProviderClient{}
}

func withProvider() {
	Provider.init()
	for key, conf := range config.Spec.SMTP {
		switch strings.ToLower(key) {
		case "google":
			Provider.Google = NewSMTP(conf)
		case "qq":
			Provider.QQ = NewSMTP(conf)
		}
	}

	for key, conf := range config.Spec.SMS {
		switch strings.ToLower(key) {
		case "aliyun":
			Provider.Aliyun = NewAliyun(conf)
		case "tencent":
			Provider.Tencent = NewTencent(conf)
		}
	}
}

func NewSMTP(conf *config.SmtpConf) *smtp.Client {
	return nil
}

func NewAliyun(conf *config.SmsConf) *dysmsapi.Client {

	config := new(credentials.Config).
		SetType("access_key").
		SetAccessKeyId(conf.AccessKeyId).
		SetAccessKeySecret(conf.AccessKeySecret)

	akCredential, err := credentials.NewCredential(config)
	if err != nil {
		panic(err)
	}

	cfg := &AliYunClient.Config{
		Endpoint:   &conf.Endpoint,
		Credential: akCredential,
	}

	client, err := dysmsapi.NewClient(cfg)
	if err != nil {
		panic(err)
	}

	return client
}

func NewTencent(conf *config.SmsConf) *TencentCloud.Client {
	credential := common.NewCredential(conf.AccessKeyId, conf.AccessKeySecret)
	clientProfile := profile.NewClientProfile()
	clientProfile.HttpProfile.Endpoint = conf.Endpoint
	client, err := TencentCloud.NewClient(credential, conf.Region, clientProfile)

	if err != nil {
		panic(err)
	}

	return client
}
