//! Moderation-related database queries.

use sqlx::PgPool;
use uuid::Uuid;

use crate::models::ActionType;
use chattyness_error::AppError;

/// Log a moderation action to the realm audit log.
pub async fn log_moderation_action(
    pool: &PgPool,
    realm_id: Uuid,
    moderator_id: Uuid,
    action_type: ActionType,
    target_user_id: Option<Uuid>,
    reason: &str,
    metadata: serde_json::Value,
) -> Result<(), AppError> {
    sqlx::query(
        r#"
        INSERT INTO realm.moderation_actions (
            realm_id,
            action_type,
            target_user_id,
            moderator_id,
            reason,
            metadata
        )
        VALUES ($1, $2, $3, $4, $5, $6)
        "#,
    )
    .bind(realm_id)
    .bind(action_type)
    .bind(target_user_id)
    .bind(moderator_id)
    .bind(reason)
    .bind(metadata)
    .execute(pool)
    .await?;

    Ok(())
}

/// Log a moderation action using a connection (for RLS support).
pub async fn log_moderation_action_conn(
    conn: &mut sqlx::PgConnection,
    realm_id: Uuid,
    moderator_id: Uuid,
    action_type: ActionType,
    target_user_id: Option<Uuid>,
    reason: &str,
    metadata: serde_json::Value,
) -> Result<(), AppError> {
    sqlx::query(
        r#"
        INSERT INTO realm.moderation_actions (
            realm_id,
            action_type,
            target_user_id,
            moderator_id,
            reason,
            metadata
        )
        VALUES ($1, $2, $3, $4, $5, $6)
        "#,
    )
    .bind(realm_id)
    .bind(action_type)
    .bind(target_user_id)
    .bind(moderator_id)
    .bind(reason)
    .bind(metadata)
    .execute(conn)
    .await?;

    Ok(())
}
