package models

import (
	"time"

	"github.com/google/uuid"
)

// EmailTemplateType defines the types of transactional emails
const (
	// Auth & Security
	EmailTypeWelcome            = "welcome"
	EmailTypeEmailVerification  = "email_verification"
	EmailTypePasswordReset      = "password_reset"
	EmailTypePasswordChanged    = "password_changed"
	EmailType2FAEnabled         = "2fa_enabled"
	EmailType2FADisabled        = "2fa_disabled"
	EmailTypeNewDeviceLogin     = "new_device_login"
	EmailTypeSuspiciousActivity = "suspicious_activity"
	EmailTypeAccountLocked      = "account_locked"
	EmailTypeAccountUnlocked    = "account_unlocked"

	// Account Lifecycle
	EmailTypeDeletionRequested = "deletion_requested"
	EmailTypeDeletionConfirmed = "deletion_confirmed"
	EmailTypeDataExportReady   = "data_export_ready"
	EmailTypeEmailChanged      = "email_changed"
	EmailTypeEmailChangeVerify = "email_change_verify"

	// Consent-related
	EmailTypeNewVersionPublished      = "new_version_published"
	EmailTypeConsentReminder          = "consent_reminder"
	EmailTypeConsentDeadlineWarning   = "consent_deadline_warning"
	EmailTypeAccountSuspended         = "account_suspended"
)

// EmailTemplate represents a template for transactional emails (like LegalDocument)
type EmailTemplate struct {
	ID          uuid.UUID `json:"id" db:"id"`
	Type        string    `json:"type" db:"type"`             // One of EmailType constants
	Name        string    `json:"name" db:"name"`             // Human-readable name
	Description *string   `json:"description" db:"description"`
	IsActive    bool      `json:"is_active" db:"is_active"`
	SortOrder   int       `json:"sort_order" db:"sort_order"`
	CreatedAt   time.Time `json:"created_at" db:"created_at"`
	UpdatedAt   time.Time `json:"updated_at" db:"updated_at"`
}

// EmailTemplateVersion represents a specific version of an email template (like DocumentVersion)
type EmailTemplateVersion struct {
	ID                 uuid.UUID  `json:"id" db:"id"`
	TemplateID         uuid.UUID  `json:"template_id" db:"template_id"`
	Version            string     `json:"version" db:"version"`     // Semver: 1.0.0
	Language           string     `json:"language" db:"language"`   // ISO 639-1: de, en
	Subject            string     `json:"subject" db:"subject"`     // Email subject line
	BodyHTML           string     `json:"body_html" db:"body_html"` // HTML version
	BodyText           string     `json:"body_text" db:"body_text"` // Plain text version
	Summary            *string    `json:"summary" db:"summary"`     // Change summary
	Status             string     `json:"status" db:"status"`       // draft, review, approved, published, archived
	PublishedAt        *time.Time `json:"published_at" db:"published_at"`
	ScheduledPublishAt *time.Time `json:"scheduled_publish_at" db:"scheduled_publish_at"`
	CreatedBy          *uuid.UUID `json:"created_by" db:"created_by"`
	ApprovedBy         *uuid.UUID `json:"approved_by" db:"approved_by"`
	ApprovedAt         *time.Time `json:"approved_at" db:"approved_at"`
	CreatedAt          time.Time  `json:"created_at" db:"created_at"`
	UpdatedAt          time.Time  `json:"updated_at" db:"updated_at"`
}

// EmailTemplateApproval tracks approval workflow for email templates
type EmailTemplateApproval struct {
	ID         uuid.UUID `json:"id" db:"id"`
	VersionID  uuid.UUID `json:"version_id" db:"version_id"`
	ApproverID uuid.UUID `json:"approver_id" db:"approver_id"`
	Action     string    `json:"action" db:"action"` // submitted_for_review, approved, rejected, published
	Comment    *string   `json:"comment,omitempty" db:"comment"`
	CreatedAt  time.Time `json:"created_at" db:"created_at"`
}

// EmailSendLog tracks sent emails for audit purposes
type EmailSendLog struct {
	ID          uuid.UUID  `json:"id" db:"id"`
	UserID      *uuid.UUID `json:"user_id,omitempty" db:"user_id"`
	VersionID   uuid.UUID  `json:"version_id" db:"version_id"`
	Recipient   string     `json:"recipient" db:"recipient"` // Email address
	Subject     string     `json:"subject" db:"subject"`
	Status      string     `json:"status" db:"status"` // queued, sent, delivered, bounced, failed
	ErrorMsg    *string    `json:"error_msg,omitempty" db:"error_msg"`
	Variables   *string    `json:"variables,omitempty" db:"variables"` // JSON of template variables used
	SentAt      *time.Time `json:"sent_at,omitempty" db:"sent_at"`
	DeliveredAt *time.Time `json:"delivered_at,omitempty" db:"delivered_at"`
	CreatedAt   time.Time  `json:"created_at" db:"created_at"`
}

// EmailTemplateSettings stores global email settings (logo, signature, etc.)
type EmailTemplateSettings struct {
	ID             uuid.UUID  `json:"id" db:"id"`
	LogoURL        *string    `json:"logo_url" db:"logo_url"`
	LogoBase64     *string    `json:"logo_base64" db:"logo_base64"` // For embedding in emails
	CompanyName    string     `json:"company_name" db:"company_name"`
	SenderName     string     `json:"sender_name" db:"sender_name"`
	SenderEmail    string     `json:"sender_email" db:"sender_email"`
	ReplyToEmail   *string    `json:"reply_to_email" db:"reply_to_email"`
	FooterHTML     *string    `json:"footer_html" db:"footer_html"`
	FooterText     *string    `json:"footer_text" db:"footer_text"`
	PrimaryColor   string     `json:"primary_color" db:"primary_color"`     // Hex color
	SecondaryColor string     `json:"secondary_color" db:"secondary_color"` // Hex color
	UpdatedAt      time.Time  `json:"updated_at" db:"updated_at"`
	UpdatedBy      *uuid.UUID `json:"updated_by" db:"updated_by"`
}

// ========================================
// E-Mail Template DTOs
// ========================================

// CreateEmailTemplateRequest for creating a new email template type
type CreateEmailTemplateRequest struct {
	Type        string  `json:"type" binding:"required"`
	Name        string  `json:"name" binding:"required"`
	Description *string `json:"description"`
}

// CreateEmailTemplateVersionRequest for creating a new version of an email template
type CreateEmailTemplateVersionRequest struct {
	TemplateID string  `json:"template_id" binding:"required"`
	Version    string  `json:"version" binding:"required"`
	Language   string  `json:"language" binding:"required"`
	Subject    string  `json:"subject" binding:"required"`
	BodyHTML   string  `json:"body_html" binding:"required"`
	BodyText   string  `json:"body_text" binding:"required"`
	Summary    *string `json:"summary"`
}

// UpdateEmailTemplateVersionRequest for updating a version
type UpdateEmailTemplateVersionRequest struct {
	Subject  *string `json:"subject"`
	BodyHTML *string `json:"body_html"`
	BodyText *string `json:"body_text"`
	Summary  *string `json:"summary"`
	Status   *string `json:"status"`
}

// UpdateEmailTemplateSettingsRequest for updating global settings
type UpdateEmailTemplateSettingsRequest struct {
	LogoURL        *string `json:"logo_url"`
	LogoBase64     *string `json:"logo_base64"`
	CompanyName    *string `json:"company_name"`
	SenderName     *string `json:"sender_name"`
	SenderEmail    *string `json:"sender_email"`
	ReplyToEmail   *string `json:"reply_to_email"`
	FooterHTML     *string `json:"footer_html"`
	FooterText     *string `json:"footer_text"`
	PrimaryColor   *string `json:"primary_color"`
	SecondaryColor *string `json:"secondary_color"`
}

// EmailTemplateWithVersion combines template info with its latest published version
type EmailTemplateWithVersion struct {
	Template      EmailTemplate         `json:"template"`
	LatestVersion *EmailTemplateVersion `json:"latest_version,omitempty"`
}

// SendTestEmailRequest for sending a test email
type SendTestEmailRequest struct {
	VersionID string            `json:"version_id" binding:"required"`
	Recipient string            `json:"recipient" binding:"required,email"`
	Variables map[string]string `json:"variables"` // Template variable overrides
}

// EmailPreviewResponse for previewing an email
type EmailPreviewResponse struct {
	Subject  string `json:"subject"`
	BodyHTML string `json:"body_html"`
	BodyText string `json:"body_text"`
}

// EmailTemplateVariables defines available variables for each template type
type EmailTemplateVariables struct {
	TemplateType string            `json:"template_type"`
	Variables    []string          `json:"variables"`
	Descriptions map[string]string `json:"descriptions"`
}

// EmailStats represents statistics about email sends
type EmailStats struct {
	TotalSent    int     `json:"total_sent"`
	Delivered    int     `json:"delivered"`
	Bounced      int     `json:"bounced"`
	Failed       int     `json:"failed"`
	DeliveryRate float64 `json:"delivery_rate"`
	RecentSent   int     `json:"recent_sent"` // Last 7 days
}
