package mailer

import (
	"os"
	"strconv"
	"strings"
)

type Config struct {
	Host     string
	Port     int
	Username string
	Password string
	From     string
	StartTLS bool
}

func ConfigFromEnv() (Config, error) {
	var cfg Config

	cfg.Host = strings.TrimSpace(os.Getenv("SMTP_HOST"))
	cfg.Username = strings.TrimSpace(os.Getenv("SMTP_USERNAME"))
	cfg.Password = os.Getenv("SMTP_PASSWORD")
	cfg.From = strings.TrimSpace(os.Getenv("SMTP_FROM"))

	portStr := strings.TrimSpace(os.Getenv("SMTP_PORT"))
	if portStr == "" {
		cfg.Port = 587
	} else {
		p, err := strconv.Atoi(portStr)
		if err != nil {
			return Config{}, err
		}
		cfg.Port = p
	}

	startTLS := strings.TrimSpace(os.Getenv("SMTP_STARTTLS"))
	if startTLS == "" {
		cfg.StartTLS = true
	} else {
		cfg.StartTLS = strings.EqualFold(startTLS, "true") || startTLS == "1"
	}

	// minimal validation
	if cfg.Host == "" || cfg.Username == "" || cfg.Password == "" || cfg.From == "" || cfg.Port <= 0 {
		return Config{}, ErrInvalidConfig
	}

	return cfg, nil
}
