package services

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

type EmailService struct {
	Host      string
	Port      string
	User      string
	Pass      string
	FromEmail string
	FromName  string
}

func NewEmailService(host, port, user, pass, fromEmail, fromName string) *EmailService {
	return &EmailService{
		Host:      host,
		Port:      port,
		User:      user,
		Pass:      pass,
		FromEmail: fromEmail,
		FromName:  fromName,
	}
}

func (s *EmailService) IsConfigured() bool {
	return s.Host != "" && s.User != "" && s.Pass != ""
}

func (s *EmailService) SendHTML(to, subject, htmlBody, textBody string) error {
	if !s.IsConfigured() {
		fmt.Printf("[Email] Skipping - not configured. Would send to: %s, Subject: %s\n", to, subject)
		return nil
	}

	from := fmt.Sprintf("%s <%s>", s.FromName, s.FromEmail)
	if s.FromName == "" {
		from = s.FromEmail
	}

	msg := buildMessage(from, to, subject, htmlBody, textBody)

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

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

func buildMessage(from, to, subject, htmlBody, textBody string) string {
	headers := make(map[string]string)
	headers["From"] = from
	headers["To"] = to
	headers["Subject"] = subject
	headers["MIME-Version"] = "1.0"
	headers["Content-Type"] = "multipart/alternative; boundary=\"boundary123\""

	var msg strings.Builder
	for k, v := range headers {
		msg.WriteString(fmt.Sprintf("%s: %s\r\n", k, v))
	}
	msg.WriteString("\r\n")

	msg.WriteString("--boundary123\r\n")
	msg.WriteString("Content-Type: text/plain; charset=\"UTF-8\"\r\n\r\n")
	msg.WriteString(textBody)
	msg.WriteString("\r\n")

	msg.WriteString("--boundary123\r\n")
	msg.WriteString("Content-Type: text/html; charset=\"UTF-8\"\r\n\r\n")
	msg.WriteString(htmlBody)
	msg.WriteString("\r\n")

	msg.WriteString("--boundary123--\r\n")

	return msg.String()
}
