package auth

import (
	"fmt"
	"net/smtp"
	"strings"

	"bountyboard/internal/config"
)

// Mailer sends plain-text email via SMTP (net/smtp, STARTTLS when offered).
// All features depending on it stay disabled until SMTP_HOST is set (§7).
type Mailer struct {
	cfg config.SMTP
}

func NewMailer(cfg config.SMTP) *Mailer { return &Mailer{cfg: cfg} }

func (m *Mailer) Enabled() bool { return m.cfg.Enabled() }

func (m *Mailer) Send(to, subject, body string) error {
	if !m.Enabled() {
		return fmt.Errorf("smtp is not configured")
	}
	addr := fmt.Sprintf("%s:%d", m.cfg.Host, m.cfg.Port)
	msg := strings.Join([]string{
		"From: " + m.cfg.From,
		"To: " + to,
		"Subject: " + subject,
		"MIME-Version: 1.0",
		"Content-Type: text/plain; charset=utf-8",
		"",
		body,
	}, "\r\n")
	var a smtp.Auth
	if m.cfg.User != "" {
		a = smtp.PlainAuth("", m.cfg.User, m.cfg.Password, m.cfg.Host)
	}
	if err := smtp.SendMail(addr, a, m.cfg.From, []string{to}, []byte(msg)); err != nil {
		return fmt.Errorf("smtp send: %w", err)
	}
	return nil
}
