use loco_rs::prelude::*;
use sea_orm::{ActiveModelTrait, Set};

use crate::{
    controllers::admin::AdminIdentity,
    models::_entities::admin_audit_logs,
};

pub async fn log_event(
    ctx: &AppContext,
    actor: Option<&AdminIdentity>,
    action: &str,
    target_type: &str,
    target_id: Option<String>,
    target_label: Option<String>,
    metadata: Option<serde_json::Value>,
) -> Result<()> {
    admin_audit_logs::ActiveModel {
        actor_username: Set(actor.map(|item| item.username.clone())),
        actor_email: Set(actor.and_then(|item| item.email.clone())),
        actor_source: Set(actor.map(|item| item.source.clone())),
        action: Set(action.to_string()),
        target_type: Set(target_type.to_string()),
        target_id: Set(target_id),
        target_label: Set(target_label),
        metadata: Set(metadata),
        ..Default::default()
    }
    .insert(&ctx.db)
    .await?;

    Ok(())
}
