//! Inventory API handlers for user UI.
//!
//! Handles inventory listing and item management.

use axum::Json;
use axum::extract::{Path, State};
use sqlx::PgPool;
use uuid::Uuid;

use chattyness_db::{
    models::{InventoryResponse, PublicPropsResponse},
    queries::{inventory, realms},
};
use chattyness_error::AppError;

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

/// Get user's full inventory.
///
/// GET /api/inventory
pub async fn get_inventory(
    rls_conn: RlsConn,
    AuthUser(user): AuthUser,
) -> Result<Json<InventoryResponse>, AppError> {
    let mut conn = rls_conn.acquire().await;

    let items = inventory::list_user_inventory(&mut *conn, user.id).await?;

    Ok(Json(InventoryResponse { items }))
}

/// Drop an item from inventory.
///
/// DELETE /api/inventory/{item_id}
pub async fn drop_item(
    rls_conn: RlsConn,
    AuthUser(user): AuthUser,
    Path(item_id): Path<Uuid>,
) -> Result<Json<serde_json::Value>, AppError> {
    let mut conn = rls_conn.acquire().await;

    inventory::drop_inventory_item(&mut *conn, user.id, item_id).await?;

    Ok(Json(serde_json::json!({ "success": true })))
}

/// Get public server props.
///
/// GET /api/inventory/server
pub async fn get_server_props(
    State(pool): State<PgPool>,
) -> Result<Json<PublicPropsResponse>, AppError> {
    let props = inventory::list_public_server_props(&pool).await?;

    Ok(Json(PublicPropsResponse { props }))
}

/// Get public realm props.
///
/// GET /api/realms/{slug}/inventory
pub async fn get_realm_props(
    State(pool): State<PgPool>,
    Path(slug): Path<String>,
) -> Result<Json<PublicPropsResponse>, AppError> {
    // Get the realm by slug to get its ID
    let realm = realms::get_realm_by_slug(&pool, &slug)
        .await?
        .ok_or_else(|| AppError::NotFound(format!("Realm '{}' not found", slug)))?;

    let props = inventory::list_public_realm_props(&pool, realm.id).await?;

    Ok(Json(PublicPropsResponse { props }))
}
