package repository

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

	"gopkg.in/gomail.v2"
)

type SMTPMailUseCaseParam struct {
	Conf config.SMTPConfig
}

type SMTPMailRepository struct {
	Client *gomail.Dialer
}

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

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

	// 構建郵件
	m := gomail.NewMessage()

	if req.SenderName != "" {
		m.SetAddressHeader("From", req.From, req.SenderName)
	} else {
		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 {
		return err
	}

	return nil
}
