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

/// 审计日志（SMTP 事件 + 管理操作）
#[derive(Clone, Debug, PartialEq, DeriveEntityModel, Serialize, Deserialize)]
#[sea_orm(table_name = "audit_logs")]
pub struct Model {
    #[sea_orm(primary_key)]
    pub id: i64,
    /// smtp_connect | smtp_rcpt | smtp_accept | smtp_reject | admin_* | ...
    pub event_type: String,
    pub source_ip: Option<String>,
    pub helo: Option<String>,
    pub mail_from: Option<String>,
    pub rcpt_to: Option<String>,
    /// accept | defer | reject | quarantine | ...
    pub action: String,
    pub reason: Option<String>,
    /// 管理操作时填 user_id
    pub operator_id: Option<String>,
    /// 被操作资源类型：user | mailbox | email | attachment | blacklist | credit_rule
    pub target_type: Option<String>,
    /// 被操作资源 ID，统一使用字符串兼容不同主键类型
    pub target_id: Option<String>,
    /// 扩展审计上下文与批次 ID
    #[sea_orm(column_type = "Text", nullable)]
    pub metadata_json: Option<String>,
    pub created_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.created_at = Set(chrono::Utc::now().naive_utc());
        }
        Ok(value)
    }
}
