use sea_orm::entity::prelude::*;
use sea_orm::Set;
use serde::{Deserialize, Serialize};

/// 接收到的邮件（含安全与审计字段）
#[derive(Clone, Debug, PartialEq, DeriveEntityModel, Serialize, Deserialize)]
#[sea_orm(table_name = "emails")]
pub struct Model {
    #[sea_orm(primary_key)]
    pub id: i64,
    /// 所属邮箱 ID（FK mailboxes.id）
    pub mailbox_id: i64,
    /// 冗余：所属用户 ID，便于按用户聚合
    pub user_id: String,
    /// 完整收件地址
    pub recipient: String,
    /// envelope MAIL FROM
    pub mail_from: String,
    /// envelope RCPT TO
    pub rcpt_to: String,
    /// 发件人显示名
    pub sender_name: Option<String>,
    pub subject: Option<String>,
    pub text_body: Option<String>,
    pub html_body: Option<String>,
    /// 来源 IP
    pub source_ip: String,
    /// SMTP HELO/EHLO
    pub helo: Option<String>,
    /// PTR 反查结果
    pub ptr_result: Option<String>,
    /// SPF 结果
    pub spf_result: Option<String>,
    /// DKIM 结果
    pub dkim_result: Option<String>,
    /// DMARC 结果
    pub dmarc_result: Option<String>,
    /// 滥用评分 0-100
    pub abuse_score: i32,
    /// 状态：received | quarantined | rejected
    pub status: String,
    pub size_bytes: i64,
    /// Message-ID 头
    pub message_id: Option<String>,
    pub received_at: DateTime,
    /// 邮件保留期截止时间（默认 received + email_ttl_days）
    pub expires_at: DateTime,
}

#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
pub enum Relation {}

#[async_trait::async_trait]
impl ActiveModelBehavior for ActiveModel {
    async fn before_save<C: ConnectionTrait>(self, _: &C, insert: bool) -> Result<Self, DbErr> {
        let mut value = self;
        if insert {
            value.received_at = Set(chrono::Utc::now().naive_utc());
        }
        Ok(value)
    }
}
