//! Channel-related database queries.

use sqlx::PgExecutor;
use uuid::Uuid;

use chattyness_error::AppError;

/// Minimal channel info for WebSocket validation.
#[derive(Debug, Clone)]
#[cfg_attr(feature = "ssr", derive(sqlx::FromRow))]
pub struct ChannelInfo {
    /// Channel ID.
    pub id: Uuid,
    /// Scene ID this channel belongs to.
    pub scene_id: Uuid,
    /// Realm ID (from the scene).
    pub realm_id: Uuid,
}

/// Get channel info by ID.
///
/// Returns the channel with its associated scene and realm IDs.
pub async fn get_channel_info<'e>(
    executor: impl PgExecutor<'e>,
    channel_id: Uuid,
) -> Result<Option<ChannelInfo>, AppError> {
    let info = sqlx::query_as::<_, ChannelInfo>(
        r#"
        SELECT
            i.id,
            i.scene_id,
            s.realm_id
        FROM scene.instances i
        JOIN realm.scenes s ON s.id = i.scene_id
        WHERE i.id = $1
        "#,
    )
    .bind(channel_id)
    .fetch_optional(executor)
    .await?;

    Ok(info)
}
