use crate::domain::entities::audit_log;
use anyhow::Result;
use sea_orm::{ActiveModelTrait, DatabaseConnection, EntityTrait, QueryOrder, QuerySelect, Set};

/// 审计日志数据访问
pub struct AuditRepository {
    db: DatabaseConnection,
}

#[derive(Default)]
pub struct NewAuditLog {
    pub event_type: String,
    pub action: String,
    pub source_ip: Option<String>,
    pub helo: Option<String>,
    pub mail_from: Option<String>,
    pub rcpt_to: Option<String>,
    pub reason: Option<String>,
    pub operator_id: Option<String>,
    pub target_type: Option<String>,
    pub target_id: Option<String>,
    pub metadata_json: Option<String>,
}

impl AuditRepository {
    pub fn new(db: DatabaseConnection) -> Self {
        Self { db }
    }

    pub async fn add(&self, event: NewAuditLog) -> Result<()> {
        audit_log::ActiveModel {
            event_type: Set(event.event_type),
            action: Set(event.action),
            source_ip: Set(event.source_ip),
            helo: Set(event.helo),
            mail_from: Set(event.mail_from),
            rcpt_to: Set(event.rcpt_to),
            reason: Set(event.reason),
            operator_id: Set(event.operator_id),
            target_type: Set(event.target_type),
            target_id: Set(event.target_id),
            metadata_json: Set(event.metadata_json),
            ..Default::default()
        }
        .insert(&self.db)
        .await?;
        Ok(())
    }

    #[allow(dead_code)]
    pub async fn list_recent(&self, limit: u64) -> Result<Vec<audit_log::Model>> {
        Ok(audit_log::Entity::find()
            .order_by_desc(audit_log::Column::CreatedAt)
            .limit(limit)
            .all(&self.db)
            .await?)
    }
}
