package models

import (
    "time"
    "gorm.io/datatypes"
)

// EmailLog stores one row per attempted delivery to a recipient
type EmailLog struct {
    ID               uint              `gorm:"primaryKey" json:"id"`
    CreatedAt        time.Time         `json:"created_at"`
    UpdatedAt        time.Time         `json:"updated_at"`

    Subject          string            `json:"subject"`
    RecipientEmail   string            `json:"recipient_email" gorm:"index"`
    Type             string            `json:"type"` // newsletter|welcome|welcome_back|other
    Status           string            `json:"status"` // sent|failed
    ProviderMessageID string           `json:"provider_message_id"`
    SendError        string            `json:"send_error"`

    Token            string            `json:"token" gorm:"index"`
}

// EmailEvent records interactions: open, click, spam, unsubscribe, bounce, complaint
type EmailEvent struct {
    ID         uint              `gorm:"primaryKey" json:"id"`
    CreatedAt  time.Time         `json:"created_at"`
    EmailLogID uint              `json:"email_log_id" gorm:"index"`
    EventType  string            `json:"event_type"`
    Meta       datatypes.JSONMap `json:"meta"`
}

// NewsletterSentLog tracks sent newsletters to prevent duplicates
type NewsletterSentLog struct {
    ID              uint      `gorm:"primaryKey" json:"id"`
    NewsletterType  string    `json:"newsletter_type" gorm:"index"` // weekly|match_reminder|match_result|blog_release
    Subject         string    `json:"subject"`
    ContentIDs      string    `json:"content_ids" gorm:"type:text"` // JSON array of IDs
    RecipientsCount int       `json:"recipients_count"`
    SentAt          time.Time `json:"sent_at" gorm:"index"`
    CreatedAt       time.Time `json:"created_at"`
}

func (NewsletterSentLog) TableName() string { return "newsletter_sent_log" }

// MatchNotification tracks match alerts sent to avoid duplicates
type MatchNotification struct {
    ID               uint      `gorm:"primaryKey" json:"id"`
    MatchID          string    `json:"match_id" gorm:"index"` // External FACR match ID
    NotificationType string    `json:"notification_type"`     // reminder_48h|reminder_day|result
    SentAt           time.Time `json:"sent_at" gorm:"index"`
    RecipientsCount  int       `json:"recipients_count"`
    CreatedAt        time.Time `json:"created_at"`
}

func (MatchNotification) TableName() string { return "match_notifications" }

// BlogNotification tracks blog release notifications
type BlogNotification struct {
    ID              uint      `gorm:"primaryKey" json:"id"`
    ArticleID       uint      `json:"article_id" gorm:"uniqueIndex"`
    SentAt          time.Time `json:"sent_at" gorm:"index"`
    RecipientsCount int       `json:"recipients_count"`
    CreatedAt       time.Time `json:"created_at"`
}

func (BlogNotification) TableName() string { return "blog_notifications" }
