package repository

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

	pool "backend/pkg/library/worker_pool"

	"github.com/zeromicro/go-zero/core/logx"
	"gopkg.in/gomail.v2"
)

type SMTPMailUseCaseParam struct {
	Conf config.SMTPConfig
}

type SMTPMailRepository struct {
	Client *gomail.Dialer
	Pool   pool.WorkerPool
}

func MustSMTPUseCase(param SMTPMailUseCaseParam) repository.MailRepository {
	return &SMTPMailRepository{
		Client: gomail.NewDialer(
			param.Conf.Host,
			param.Conf.Port,
			param.Conf.Username,
			param.Conf.Password,
		),
		Pool: pool.NewWorkerPool(param.Conf.GoroutinePoolNum),
	}
}

func (repo *SMTPMailRepository) SendMail(_ context.Context, req repository.MailReq) error {
	// 用 goroutine pool 送，否則會超時
	err := repo.Pool.Submit(func() {
		m := gomail.NewMessage()
		m.SetHeader("From", req.From)
		m.SetHeader("To", req.To...)
		m.SetHeader("Subject", req.Subject)
		m.SetBody("text/html", req.Body)
		if err := repo.Client.DialAndSend(m); err != nil {
			logx.WithCallerSkip(1).WithFields(
				logx.Field("func", "MailUseCase.SendMail"),
				logx.Field("req", req),
				logx.Field("err", err),
			).Error("failed to send mail by mailgun")
		}
	})

	return err
}
