package services

import (
	"context"
	"fmt"
	"time"

	"github.com/breakpilot/consent-service/internal/models"
	"github.com/google/uuid"
)

// GetAllTemplateTypes returns all available email template types with their variables
func (s *EmailTemplateService) GetAllTemplateTypes() []models.EmailTemplateVariables {
	return []models.EmailTemplateVariables{
		{
			TemplateType: models.EmailTypeWelcome,
			Variables:    []string{"user_name", "user_email", "login_url", "support_email"},
			Descriptions: map[string]string{
				"user_name":     "Name des Benutzers",
				"user_email":    "E-Mail-Adresse des Benutzers",
				"login_url":     "URL zur Login-Seite",
				"support_email": "Support E-Mail-Adresse",
			},
		},
		{
			TemplateType: models.EmailTypeEmailVerification,
			Variables:    []string{"user_name", "verification_url", "verification_code", "expires_in"},
			Descriptions: map[string]string{
				"user_name":         "Name des Benutzers",
				"verification_url":  "URL zur E-Mail-Verifizierung",
				"verification_code": "Verifizierungscode",
				"expires_in":        "Gültigkeit des Links (z.B. '24 Stunden')",
			},
		},
		{
			TemplateType: models.EmailTypePasswordReset,
			Variables:    []string{"user_name", "reset_url", "reset_code", "expires_in", "ip_address"},
			Descriptions: map[string]string{
				"user_name":  "Name des Benutzers",
				"reset_url":  "URL zum Passwort-Reset",
				"reset_code": "Reset-Code",
				"expires_in": "Gültigkeit des Links",
				"ip_address": "IP-Adresse der Anfrage",
			},
		},
		{
			TemplateType: models.EmailTypePasswordChanged,
			Variables:    []string{"user_name", "changed_at", "ip_address", "device_info", "support_url"},
			Descriptions: map[string]string{
				"user_name":   "Name des Benutzers",
				"changed_at":  "Zeitpunkt der Änderung",
				"ip_address":  "IP-Adresse",
				"device_info": "Geräte-Informationen",
				"support_url": "URL zum Support",
			},
		},
		{
			TemplateType: models.EmailType2FAEnabled,
			Variables:    []string{"user_name", "enabled_at", "device_info", "security_url"},
			Descriptions: map[string]string{
				"user_name":    "Name des Benutzers",
				"enabled_at":   "Zeitpunkt der Aktivierung",
				"device_info":  "Geräte-Informationen",
				"security_url": "URL zu Sicherheitseinstellungen",
			},
		},
		{
			TemplateType: models.EmailType2FADisabled,
			Variables:    []string{"user_name", "disabled_at", "ip_address", "security_url"},
			Descriptions: map[string]string{
				"user_name":    "Name des Benutzers",
				"disabled_at":  "Zeitpunkt der Deaktivierung",
				"ip_address":   "IP-Adresse",
				"security_url": "URL zu Sicherheitseinstellungen",
			},
		},
		{
			TemplateType: models.EmailTypeNewDeviceLogin,
			Variables:    []string{"user_name", "login_time", "ip_address", "device_info", "location", "security_url"},
			Descriptions: map[string]string{
				"user_name":    "Name des Benutzers",
				"login_time":   "Zeitpunkt des Logins",
				"ip_address":   "IP-Adresse",
				"device_info":  "Geräte-Informationen",
				"location":     "Ungefährer Standort",
				"security_url": "URL zu Sicherheitseinstellungen",
			},
		},
		{
			TemplateType: models.EmailTypeSuspiciousActivity,
			Variables:    []string{"user_name", "activity_type", "activity_time", "ip_address", "security_url"},
			Descriptions: map[string]string{
				"user_name":     "Name des Benutzers",
				"activity_type": "Art der Aktivität",
				"activity_time": "Zeitpunkt",
				"ip_address":    "IP-Adresse",
				"security_url":  "URL zu Sicherheitseinstellungen",
			},
		},
		{
			TemplateType: models.EmailTypeAccountLocked,
			Variables:    []string{"user_name", "locked_at", "reason", "unlock_time", "support_url"},
			Descriptions: map[string]string{
				"user_name":   "Name des Benutzers",
				"locked_at":   "Zeitpunkt der Sperrung",
				"reason":      "Grund der Sperrung",
				"unlock_time": "Zeitpunkt der automatischen Entsperrung",
				"support_url": "URL zum Support",
			},
		},
		{
			TemplateType: models.EmailTypeAccountUnlocked,
			Variables:    []string{"user_name", "unlocked_at", "login_url"},
			Descriptions: map[string]string{
				"user_name":   "Name des Benutzers",
				"unlocked_at": "Zeitpunkt der Entsperrung",
				"login_url":   "URL zur Login-Seite",
			},
		},
		{
			TemplateType: models.EmailTypeDeletionRequested,
			Variables:    []string{"user_name", "requested_at", "deletion_date", "cancel_url", "data_info"},
			Descriptions: map[string]string{
				"user_name":     "Name des Benutzers",
				"requested_at":  "Zeitpunkt der Anfrage",
				"deletion_date": "Datum der endgültigen Löschung",
				"cancel_url":    "URL zum Abbrechen",
				"data_info":     "Info über zu löschende Daten",
			},
		},
		{
			TemplateType: models.EmailTypeDeletionConfirmed,
			Variables:    []string{"user_name", "deleted_at", "feedback_url"},
			Descriptions: map[string]string{
				"user_name":    "Name des Benutzers",
				"deleted_at":   "Zeitpunkt der Löschung",
				"feedback_url": "URL für Feedback",
			},
		},
		{
			TemplateType: models.EmailTypeDataExportReady,
			Variables:    []string{"user_name", "download_url", "expires_in", "file_size"},
			Descriptions: map[string]string{
				"user_name":    "Name des Benutzers",
				"download_url": "URL zum Download",
				"expires_in":   "Gültigkeit des Download-Links",
				"file_size":    "Dateigröße",
			},
		},
		{
			TemplateType: models.EmailTypeEmailChanged,
			Variables:    []string{"user_name", "old_email", "new_email", "changed_at", "support_url"},
			Descriptions: map[string]string{
				"user_name":   "Name des Benutzers",
				"old_email":   "Alte E-Mail-Adresse",
				"new_email":   "Neue E-Mail-Adresse",
				"changed_at":  "Zeitpunkt der Änderung",
				"support_url": "URL zum Support",
			},
		},
		{
			TemplateType: models.EmailTypeEmailChangeVerify,
			Variables:    []string{"user_name", "new_email", "verification_url", "expires_in"},
			Descriptions: map[string]string{
				"user_name":        "Name des Benutzers",
				"new_email":        "Neue E-Mail-Adresse",
				"verification_url": "URL zur Verifizierung",
				"expires_in":       "Gültigkeit des Links",
			},
		},
		{
			TemplateType: models.EmailTypeNewVersionPublished,
			Variables:    []string{"user_name", "document_name", "document_type", "version", "consent_url", "deadline"},
			Descriptions: map[string]string{
				"user_name":     "Name des Benutzers",
				"document_name": "Name des Dokuments",
				"document_type": "Typ des Dokuments",
				"version":       "Versionsnummer",
				"consent_url":   "URL zur Zustimmung",
				"deadline":      "Frist für die Zustimmung",
			},
		},
		{
			TemplateType: models.EmailTypeConsentReminder,
			Variables:    []string{"user_name", "document_name", "days_left", "consent_url", "deadline"},
			Descriptions: map[string]string{
				"user_name":     "Name des Benutzers",
				"document_name": "Name des Dokuments",
				"days_left":     "Verbleibende Tage",
				"consent_url":   "URL zur Zustimmung",
				"deadline":      "Frist für die Zustimmung",
			},
		},
		{
			TemplateType: models.EmailTypeConsentDeadlineWarning,
			Variables:    []string{"user_name", "document_name", "hours_left", "consent_url", "consequences"},
			Descriptions: map[string]string{
				"user_name":     "Name des Benutzers",
				"document_name": "Name des Dokuments",
				"hours_left":    "Verbleibende Stunden",
				"consent_url":   "URL zur Zustimmung",
				"consequences":  "Konsequenzen bei Nicht-Zustimmung",
			},
		},
		{
			TemplateType: models.EmailTypeAccountSuspended,
			Variables:    []string{"user_name", "suspended_at", "reason", "documents", "consent_url"},
			Descriptions: map[string]string{
				"user_name":    "Name des Benutzers",
				"suspended_at": "Zeitpunkt der Suspendierung",
				"reason":       "Grund der Suspendierung",
				"documents":    "Liste der fehlenden Zustimmungen",
				"consent_url":  "URL zur Zustimmung",
			},
		},
	}
}

// GetSettings returns global email settings
func (s *EmailTemplateService) GetSettings(ctx context.Context) (*models.EmailTemplateSettings, error) {
	var settings models.EmailTemplateSettings
	err := s.db.QueryRow(ctx, `
		SELECT id, logo_url, logo_base64, company_name, sender_name, sender_email,
		       reply_to_email, footer_html, footer_text, primary_color, secondary_color,
		       updated_at, updated_by
		FROM email_template_settings
		LIMIT 1
	`).Scan(&settings.ID, &settings.LogoURL, &settings.LogoBase64, &settings.CompanyName,
		&settings.SenderName, &settings.SenderEmail, &settings.ReplyToEmail, &settings.FooterHTML,
		&settings.FooterText, &settings.PrimaryColor, &settings.SecondaryColor,
		&settings.UpdatedAt, &settings.UpdatedBy)
	if err != nil {
		return nil, fmt.Errorf("failed to get email settings: %w", err)
	}
	return &settings, nil
}

// UpdateSettings updates global email settings
func (s *EmailTemplateService) UpdateSettings(ctx context.Context, req *models.UpdateEmailTemplateSettingsRequest, updatedBy uuid.UUID) error {
	query := "UPDATE email_template_settings SET updated_at = $1, updated_by = $2"
	args := []interface{}{time.Now(), updatedBy}
	argIdx := 3

	if req.LogoURL != nil {
		query += fmt.Sprintf(", logo_url = $%d", argIdx)
		args = append(args, *req.LogoURL)
		argIdx++
	}
	if req.LogoBase64 != nil {
		query += fmt.Sprintf(", logo_base64 = $%d", argIdx)
		args = append(args, *req.LogoBase64)
		argIdx++
	}
	if req.CompanyName != nil {
		query += fmt.Sprintf(", company_name = $%d", argIdx)
		args = append(args, *req.CompanyName)
		argIdx++
	}
	if req.SenderName != nil {
		query += fmt.Sprintf(", sender_name = $%d", argIdx)
		args = append(args, *req.SenderName)
		argIdx++
	}
	if req.SenderEmail != nil {
		query += fmt.Sprintf(", sender_email = $%d", argIdx)
		args = append(args, *req.SenderEmail)
		argIdx++
	}
	if req.ReplyToEmail != nil {
		query += fmt.Sprintf(", reply_to_email = $%d", argIdx)
		args = append(args, *req.ReplyToEmail)
		argIdx++
	}
	if req.FooterHTML != nil {
		query += fmt.Sprintf(", footer_html = $%d", argIdx)
		args = append(args, *req.FooterHTML)
		argIdx++
	}
	if req.FooterText != nil {
		query += fmt.Sprintf(", footer_text = $%d", argIdx)
		args = append(args, *req.FooterText)
		argIdx++
	}
	if req.PrimaryColor != nil {
		query += fmt.Sprintf(", primary_color = $%d", argIdx)
		args = append(args, *req.PrimaryColor)
		argIdx++
	}
	if req.SecondaryColor != nil {
		query += fmt.Sprintf(", secondary_color = $%d", argIdx)
		args = append(args, *req.SecondaryColor)
		argIdx++
	}

	_, err := s.db.Exec(ctx, query, args...)
	if err != nil {
		return fmt.Errorf("failed to update settings: %w", err)
	}
	return nil
}
