//! Avatar API handlers for user UI.
//!
//! Handles avatar data retrieval.
//! Note: Emotion switching is handled via WebSocket.

use axum::extract::Path;
use axum::Json;

use chattyness_db::{
    models::AvatarWithPaths,
    queries::{avatars, realms},
};
use chattyness_error::AppError;

use crate::auth::{AuthUser, RlsConn};

/// Get full avatar with all paths resolved.
///
/// GET /api/realms/{slug}/avatar
///
/// Returns the complete avatar data with all inventory UUIDs resolved to asset paths.
/// This enables client-side emotion availability computation and rendering without
/// additional server queries.
pub async fn get_avatar(
    rls_conn: RlsConn,
    AuthUser(user): AuthUser,
    Path(slug): Path<String>,
) -> Result<Json<AvatarWithPaths>, AppError> {
    let mut conn = rls_conn.acquire().await;

    // Get realm
    let realm = realms::get_realm_by_slug(&mut *conn, &slug)
        .await?
        .ok_or_else(|| AppError::NotFound(format!("Realm '{}' not found", slug)))?;

    // Get full avatar with paths
    let avatar = avatars::get_avatar_with_paths_conn(&mut *conn, user.id, realm.id)
        .await?
        .unwrap_or_default();

    Ok(Json(avatar))
}
