package repository

import (
	"backend/pkg/notification/config"
	"backend/pkg/notification/domain"
	"backend/pkg/notification/domain/repository"
	"context"

	"backend/pkg/library/errs/code"
	pool "backend/pkg/library/worker_pool"

	"github.com/minchao/go-mitake"
	"github.com/zeromicro/go-zero/core/logx"
)

// MitakeSMSDeliveryParam 三竹傳送參數配置
type MitakeSMSDeliveryParam struct {
	Conf *config.MitakeSMSSender
}

type MitakeSMSDeliveryRepository struct {
	Client *mitake.Client
	Pool   pool.WorkerPool
}

func (use *MitakeSMSDeliveryRepository) SendSMS(ctx context.Context, req repository.SMSMessageRequest) error {
	// 用 goroutine pool 送，否則會超時
	err := use.Pool.Submit(func() {
		message := mitake.Message{
			Dstaddr:  req.PhoneNumber,
			Destname: req.RecipientName,
			Smbody:   req.MessageContent,
		}
		_, err := use.Client.Send(message)
		if err != nil {
			logx.Error("failed to send sms via mitake")
		}
	})

	if err != nil {
		// 錯誤代碼 20-201-04
		e := domain.ThirdPartyErrorL(
			code.CloudEPNotification,
			domain.FailedToSendSMSErrorCode,
			logx.WithContext(ctx),
			[]logx.LogField{
				{Key: "req", Value: req},
				{Key: "func", Value: "MitakeSMSDeliveryRepository.Client.Send"},
				{Key: "err", Value: err.Error()},
			},
			"failed to send sns by mitake").Wrap(err)

		return e
	}

	return nil
}

func MustMitakeRepository(param MitakeSMSDeliveryParam) repository.SMSClientRepository {
	return &MitakeSMSDeliveryRepository{
		Client: mitake.NewClient(param.Conf.User, param.Conf.Password, nil),
		Pool:   pool.NewWorkerPool(param.Conf.PoolSize),
	}
}
