package service

// 邮件服务模块
// SSO 重构后，验证码发送/验证已由认证中心处理
// 此文件仅保留通用工具函数，如有需要可用于未来的邮件通知功能

import (
	"crypto/tls"
	"fmt"
	"net/smtp"

	"infogenie-backend/config"
)

// SendNotificationEmail 发送通知邮件（预留，供未来使用）
func SendNotificationEmail(to, subject, htmlBody string) error {
	return sendSMTPMail(to, subject, htmlBody)
}

func sendSMTPMail(to, subject, htmlBody string) error {
	cfg := config.Cfg.Mail
	from := cfg.Username

	headers := fmt.Sprintf("From: %s\r\nTo: %s\r\nSubject: %s\r\nMIME-Version: 1.0\r\nContent-Type: text/html; charset=UTF-8\r\n\r\n",
		from, to, subject)
	msg := headers + htmlBody

	addr := fmt.Sprintf("%s:%d", cfg.Host, cfg.Port)

	tlsConfig := &tls.Config{
		ServerName: cfg.Host,
	}

	conn, err := tls.Dial("tcp", addr, tlsConfig)
	if err != nil {
		return fmt.Errorf("TLS连接失败: %w", err)
	}

	client, err := smtp.NewClient(conn, cfg.Host)
	if err != nil {
		return fmt.Errorf("SMTP客户端创建失败: %w", err)
	}
	defer client.Quit()

	auth := smtp.PlainAuth("", cfg.Username, cfg.Password, cfg.Host)
	if err := client.Auth(auth); err != nil {
		return fmt.Errorf("SMTP认证失败: %w", err)
	}

	if err := client.Mail(from); err != nil {
		return err
	}
	if err := client.Rcpt(to); err != nil {
		return err
	}

	w, err := client.Data()
	if err != nil {
		return err
	}
	if _, err := w.Write([]byte(msg)); err != nil {
		return err
	}
	return w.Close()
}
