package services

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

	"github.com/sujit-baniya/fiber-boilerplate/app"
	"github.com/sujit-baniya/fiber-boilerplate/pkg/models"
)

// soporteSendMail envía un correo usando la configuración SMTP del webhook de soporte.
// Si no hay SMTP configurado, usa app.Http.Mail como fallback.
func soporteSendMail(to, subject, htmlBody string) error {
	cfg, err := models.GetSoporteWebhookActivo()
	if err != nil || cfg == nil || cfg.SmtpHost == "" {
		return app.Http.Mail.Send(to, subject, htmlBody)
	}
	from := cfg.SmtpFromAddr
	if from == "" {
		from = cfg.EmailDestino
	}
	if from == "" {
		return app.Http.Mail.Send(to, subject, htmlBody)
	}
	fromName := cfg.SmtpFromName
	if fromName == "" {
		fromName = "Soporte"
	}
	port := cfg.SmtpPort
	if port == 0 {
		port = 587
	}
	auth := smtp.PlainAuth("", cfg.SmtpUsername, cfg.SmtpPassword, cfg.SmtpHost)
	msg := []byte(fmt.Sprintf("From: %s <%s>\r\nTo: %s\r\nSubject: %s\r\nMIME-Version: 1.0\r\nContent-Type: text/html; charset=UTF-8\r\n\r\n%s", fromName, from, to, subject, htmlBody))
	addr := fmt.Sprintf("%s:%d", cfg.SmtpHost, port)
	enc := strings.ToLower(cfg.SmtpEncryption)
	if enc == "tls" {
		tlsCfg := &tls.Config{ServerName: cfg.SmtpHost}
		conn, err := tls.Dial("tcp", addr, tlsCfg)
		if err != nil {
			return fmt.Errorf("soporte SMTP TLS: %w", err)
		}
		client, err := smtp.NewClient(conn, cfg.SmtpHost)
		if err != nil {
			conn.Close()
			return fmt.Errorf("soporte SMTP client: %w", err)
		}
		defer client.Close()
		if err = client.Auth(auth); err != nil {
			return fmt.Errorf("soporte SMTP auth: %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
		}
		_, err = w.Write(msg)
		if err != nil {
			return err
		}
		return w.Close()
	}
	if enc == "starttls" {
		tlsCfg := &tls.Config{ServerName: cfg.SmtpHost}
		conn, err := smtp.Dial(addr)
		if err != nil {
			goto fallback
		}
		if err = conn.StartTLS(tlsCfg); err != nil {
			conn.Close()
			goto fallback
		}
		if err = conn.Auth(auth); err != nil {
			conn.Close()
			return fmt.Errorf("soporte SMTP STARTTLS auth: %w", err)
		}
		return smtp.SendMail(addr, auth, from, []string{to}, msg)
	}
	return smtp.SendMail(addr, auth, from, []string{to}, msg)

fallback:
	return app.Http.Mail.Send(to, subject, htmlBody)
}

// SendSoporteAutoRespuesta envía acuse de recibo automático al crear un ticket por email
func SendSoporteAutoRespuesta(ticket *models.ProyectoTicket) {
	if ticket == nil || ticket.EmailFrom == "" {
		return
	}
	subject := fmt.Sprintf("Recibimos tu solicitud: %s", ticket.Titulo)
	mensaje := "Hemos recibido tu solicitud y te responderemos a la brevedad."
	if app.Http.Database.DB != nil {
		if cfg, err := models.GetSoporteWebhookActivo(); err == nil && cfg.MensajeAuto != "" {
			mensaje = cfg.MensajeAuto
		}
	}
	htmlBody := fmt.Sprintf(`<!DOCTYPE html>
<html><body style="font-family:Inter,sans-serif;background:#f1f5f9;padding:32px">
<div style="max-width:520px;margin:0 auto;background:#fff;border-radius:16px;padding:32px;border:1px solid #e2e8f0">
  <div style="text-align:center;margin-bottom:24px">
    <div style="width:48px;height:48px;border-radius:50%%;background:#8eb02f;display:inline-flex;align-items:center;justify-content:center;color:#fff;font-weight:700;font-size:20px">U</div>
    <h2 style="margin:12px 0 4px;color:#1e293b">Ticket recibido</h2>
    <p style="color:#64748b;font-size:14px;margin:0">Soporte U-site</p>
  </div>
  <p style="color:#334155;font-size:15px">Hola <strong>%s</strong>,</p>
  <p style="color:#334155;font-size:14px">%s</p>
  <div style="background:#f8fafc;border-radius:10px;padding:16px;margin:20px 0;border:1px solid #e2e8f0">
    <p style="margin:0 0 6px;font-size:13px;color:#64748b"><strong>Ticket:</strong> #%d</p>
    <p style="margin:0 0 6px;font-size:13px;color:#64748b"><strong>Asunto:</strong> %s</p>
    <p style="margin:0;font-size:13px;color:#64748b"><strong>Mensaje:</strong> %s</p>
  </div>
  <p style="color:#94a3b8;font-size:12px">Este es un mensaje automático. No respondas a este correo.</p>
</div></body></html>`, ticket.AutorNombre, mensaje, ticket.ID, ticket.Titulo, ticket.Descripcion)

	go func() {
		if err := soporteSendMail(ticket.EmailFrom, subject, htmlBody); err != nil {
			log.Printf("[Soporte] Error enviando auto-respuesta a %s: %v", ticket.EmailFrom, err)
		} else {
			log.Printf("[Soporte] Auto-respuesta enviada a %s (ticket #%d)", ticket.EmailFrom, ticket.ID)
		}
	}()
}

// SendSoporteNotifAdmin notifica a los admins sobre un nuevo ticket de email
func SendSoporteNotifAdmin(ticket *models.ProyectoTicket) {
	if ticket == nil {
		return
	}
	adminEmail := ""
	if app.Http.Database.DB != nil {
		if cfg, err := models.GetSmtpConfig(); err == nil {
			adminEmail = cfg.FromAddress
		}
	}
	if adminEmail == "" {
		return
	}
	subject := fmt.Sprintf("🎫 Nuevo ticket por email: %s", ticket.Titulo)
	htmlBody := fmt.Sprintf(`<!DOCTYPE html>
<html><body style="font-family:Inter,sans-serif;background:#f1f5f9;padding:32px">
<div style="max-width:520px;margin:0 auto;background:#fff;border-radius:16px;padding:32px;border:1px solid #e2e8f0">
  <div style="display:flex;align-items:center;gap:12px;margin-bottom:20px">
    <div style="width:40px;height:40px;border-radius:50%%;background:#8eb02f;display:flex;align-items:center;justify-content:center;color:#fff;font-size:18px">🎫</div>
    <div><h2 style="margin:0;color:#1e293b;font-size:17px">Nuevo ticket por email</h2>
    <p style="margin:0;color:#64748b;font-size:13px">De: <strong>%s</strong> &lt;%s&gt;</p></div>
  </div>
  <div style="background:#f8fafc;border-radius:10px;padding:16px;margin-bottom:20px;border:1px solid #e2e8f0">
    <p style="margin:0 0 6px;font-size:14px;color:#334155"><strong>Asunto:</strong> %s</p>
    <p style="margin:0;font-size:14px;color:#334155"><strong>Mensaje:</strong> %s</p>
  </div>
  <a href="%s/app/tickets?ticket=%d" style="display:block;text-align:center;background:#8eb02f;color:#fff;padding:12px 24px;border-radius:10px;font-weight:600;text-decoration:none;font-size:15px">Ver ticket</a>
</div></body></html>`, ticket.AutorNombre, ticket.EmailFrom, ticket.Titulo, ticket.Descripcion, absAppURL(""), ticket.ID)

	go func() {
		if err := soporteSendMail(adminEmail, subject, htmlBody); err != nil {
			log.Printf("[Soporte] Error notificando admin: %v", err)
		}
	}()
}
