package utils

import (
	"crypto/rand"
	"encoding/hex"
	"fmt"
	"net/smtp"
)

type EmailService struct {
	config *EmailConfig
	auth   smtp.Auth
}

func NewEmailService(config *EmailConfig) *EmailService {
	auth := smtp.PlainAuth("", config.Username, config.Password, config.Host)
	return &EmailService{
		config: config,
		auth:   auth,
	}
}

func (s *EmailService) SendEmail(to, subject, body string) error {
	addr := fmt.Sprintf("%s:%d", s.config.Host, s.config.Port)
	msg := []byte(fmt.Sprintf("To: %s\r\n"+
		"Subject: %s\r\n"+
		"Content-Type: text/html; charset=UTF-8\r\n"+
		"\r\n"+
		"%s\r\n", to, subject, body))

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

func GenerateResetToken() (string, error) {
	b := make([]byte, 16)
	if _, err := rand.Read(b); err != nil {
		return "", err
	}
	return hex.EncodeToString(b), nil
}
