package repository

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

	"github.com/minchao/go-mitake"
)

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

type MitakeSMSDeliveryRepository struct {
	Client *mitake.Client
}

func (repo *MitakeSMSDeliveryRepository) SendSMS(ctx context.Context, req repository.SMSMessageRequest) error {
	// 檢查 context 是否已取消
	if ctx.Err() != nil {
		return ctx.Err()
	}

	// 構建簡訊訊息
	message := mitake.Message{
		Dstaddr:  req.PhoneNumber,
		Destname: req.RecipientName,
		Smbody:   req.MessageContent,
	}

	// 直接發送，不使用 goroutine pool
	// 讓 delivery usecase 統一管理重試和超時
	_, err := repo.Client.Send(message)
	if err != nil {
		return err
	}

	return nil
}

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