// Package mailer provides SMTP email sending for delivering
// security reports to booth visitors.
package mailer

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

// Config holds SMTP server configuration.
type Config struct {
	Host     string
	Port     int
	Username string
	Password string
	From     string
}

// DefaultConfig returns the default SMTP configuration for the booth.
func DefaultConfig() Config {
	return Config{
		Host:     "smtp.openxchange.eu",
		Port:     587,
		Username: "post@sechpoint.app",
		Password: "0@pYAY14mB",
		From:     "post@sechpoint.app",
	}
}

// ConfigFromEnv reads SMTP configuration from environment variables.
// Falls back to defaults if env vars are not set.
// Supported env vars: SMTP_HOST, SMTP_PORT, SMTP_USERNAME, SMTP_PASSWORD, SMTP_FROM
func ConfigFromEnv() Config {
	cfg := DefaultConfig()
	if v := os.Getenv("SMTP_HOST"); v != "" {
		cfg.Host = v
	}
	if v := os.Getenv("SMTP_PORT"); v != "" {
		if port, err := strconv.Atoi(v); err == nil {
			cfg.Port = port
		}
	}
	if v := os.Getenv("SMTP_USERNAME"); v != "" {
		cfg.Username = v
	}
	if v := os.Getenv("SMTP_PASSWORD"); v != "" {
		cfg.Password = v
	}
	if v := os.Getenv("SMTP_FROM"); v != "" {
		cfg.From = v
	}
	return cfg
}

// Mailer sends emails via SMTP.
type Mailer struct {
	config Config
}

// New creates a new Mailer with the given configuration.
func New(cfg Config) *Mailer {
	return &Mailer{config: cfg}
}

// SendReport sends an email with a link to the security report.
// The recipient receives a brief message with the report URL.
func (m *Mailer) SendReport(to, reportURL string) error {
	auth := smtp.PlainAuth("", m.config.Username, m.config.Password, m.config.Host)

	subject := "Your API Attack Surface Discovery Report"
	body := fmt.Sprintf(`From: %s
To: %s
Subject: %s
MIME-Version: 1.0
Content-Type: text/html; charset="UTF-8"

<!DOCTYPE html>
<html>
<head><meta charset="utf-8"></head>
<body style="font-family: Arial, sans-serif; background: #0f172a; color: #f1f5f9; padding: 2rem;">
<div style="max-width: 600px; margin: 0 auto; background: #1e293b; border-radius: 12px; padding: 2rem;">
  <h1 style="color: #3b82f6; font-size: 1.5rem;">Your API Attack Surface Report</h1>
  <p>Thank you for participating in the GITEX 2026 Security Simulation.</p>
  <p>Your personalized resilience report is ready:</p>
  <div style="text-align: center; margin: 2rem 0;">
    <a href="%s" style="display: inline-block; background: linear-gradient(90deg, #3b82f6, #8b5cf6); color: white; padding: 1rem 2rem; border-radius: 8px; text-decoration: none; font-weight: bold;">View Your Report</a>
  </div>
  <p style="color: #94a3b8; font-size: 0.9rem;">This report contains your API attack surface assessment, WAF analysis, and remediation recommendations.</p>
  <hr style="border: 1px solid #334155; margin: 2rem 0;">
  <p style="color: #64748b; font-size: 0.8rem;">GITEX 2026 — API Attack Surface Discovery by sechpoint.app</p>
</div>
</body>
</html>`, m.config.From, to, subject, reportURL)

	msg := []byte(body)
	addr := fmt.Sprintf("%s:%d", m.config.Host, m.config.Port)

	// Some SMTP servers require the sender to match the authenticated user
	if !strings.Contains(m.config.From, "@") {
		return fmt.Errorf("mailer: invalid From address: %s", m.config.From)
	}

	err := smtp.SendMail(addr, auth, m.config.From, []string{to}, msg)
	if err != nil {
		return fmt.Errorf("mailer: failed to send email to %s: %w", to, err)
	}

	return nil
}
