//! Server configuration database queries.
//!
//! These queries are used by the owner interface and require the chattyness_owner role.

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

use crate::models::{ServerConfig, UpdateServerConfigRequest};
use chattyness_error::AppError;

/// The fixed UUID for the singleton server config row.
pub fn server_config_id() -> Uuid {
    Uuid::parse_str("00000000-0000-0000-0000-000000000001").unwrap()
}

/// Get the server configuration.
pub async fn get_server_config(pool: &PgPool) -> Result<ServerConfig, AppError> {
    let config = sqlx::query_as::<_, ServerConfig>(
        r#"
        SELECT
            id,
            name,
            description,
            welcome_message,
            max_users_per_channel,
            message_rate_limit,
            message_rate_window_seconds,
            allow_guest_access,
            allow_user_uploads,
            require_email_verification,
            created_at,
            updated_at
        FROM server.config
        WHERE id = $1
        "#,
    )
    .bind(server_config_id())
    .fetch_one(pool)
    .await?;

    Ok(config)
}

/// Update the server configuration.
pub async fn update_server_config(
    pool: &PgPool,
    req: &UpdateServerConfigRequest,
) -> Result<ServerConfig, AppError> {
    let config = sqlx::query_as::<_, ServerConfig>(
        r#"
        UPDATE server.config
        SET
            name = $1,
            description = $2,
            welcome_message = $3,
            max_users_per_channel = $4,
            message_rate_limit = $5,
            message_rate_window_seconds = $6,
            allow_guest_access = $7,
            allow_user_uploads = $8,
            require_email_verification = $9,
            updated_at = now()
        WHERE id = $10
        RETURNING
            id,
            name,
            description,
            welcome_message,
            max_users_per_channel,
            message_rate_limit,
            message_rate_window_seconds,
            allow_guest_access,
            allow_user_uploads,
            require_email_verification,
            created_at,
            updated_at
        "#,
    )
    .bind(&req.name)
    .bind(&req.description)
    .bind(&req.welcome_message)
    .bind(req.max_users_per_channel)
    .bind(req.message_rate_limit)
    .bind(req.message_rate_window_seconds)
    .bind(req.allow_guest_access)
    .bind(req.allow_user_uploads)
    .bind(req.require_email_verification)
    .bind(server_config_id())
    .fetch_one(pool)
    .await?;

    Ok(config)
}
