use crate::domain::entities::{abuse_event, abuse_rule};
use anyhow::Result;
use sea_orm::{
    ActiveModelTrait, ColumnTrait, DatabaseConnection, EntityTrait, QueryFilter, QueryOrder,
    QuerySelect, Set,
};

/// 滥用规则与事件数据访问
pub struct AbuseRepository {
    db: DatabaseConnection,
}

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

    #[allow(dead_code)]
    pub async fn list_rules(&self, enabled_only: bool) -> Result<Vec<abuse_rule::Model>> {
        let mut q = abuse_rule::Entity::find();
        if enabled_only {
            q = q.filter(abuse_rule::Column::Enabled.eq(true));
        }
        Ok(q.all(&self.db).await?)
    }

    pub async fn add_event(
        &self,
        rule_id: i64,
        target: String,
        detail: Option<String>,
    ) -> Result<()> {
        abuse_event::ActiveModel {
            rule_id: Set(rule_id),
            target: Set(target),
            detail: Set(detail),
            ..Default::default()
        }
        .insert(&self.db)
        .await?;
        Ok(())
    }

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