package tools

import (
	"fmt"
	"log"
	"net/smtp"
	"os"
)

// SMTPConfig holds email server configuration.
type SMTPConfig struct {
	Host     string
	Port     int
	User     string
	Password string
	From     string
}

// LoadSMTPConfig loads SMTP settings from environment variables.
func LoadSMTPConfig() *SMTPConfig {
	cfg := &SMTPConfig{
		Host:     os.Getenv("SMTP_HOST"),
		Port:     587,
		User:     os.Getenv("SMTP_USER"),
		Password: os.Getenv("SMTP_PASSWORD"),
		From:     os.Getenv("SMTP_FROM"),
	}
	return cfg
}

// SendEmail sends a simple email. Returns error if SMTP is not configured.
func SendEmail(cfg *SMTPConfig, to, subject, body string) error {
	if cfg.Host == "" {
		log.Printf("email: SMTP not configured, would send to=%s subject=%s", to, subject)
		return nil // Silently succeed if not configured
	}

	msg := fmt.Sprintf("From: %s\r\nTo: %s\r\nSubject: %s\r\nContent-Type: text/html; charset=utf-8\r\n\r\n%s",
		cfg.From, to, subject, body)

	auth := smtp.PlainAuth("", cfg.User, cfg.Password, cfg.Host)
	addr := fmt.Sprintf("%s:%d", cfg.Host, cfg.Port)

	return smtp.SendMail(addr, auth, cfg.From, []string{to}, []byte(msg))
}
