//! Inventory-related database queries.

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

use crate::models::InventoryItem;
use chattyness_error::AppError;

/// List all inventory items for a user.
pub async fn list_user_inventory<'e>(
    executor: impl PgExecutor<'e>,
    user_id: Uuid,
) -> Result<Vec<InventoryItem>, AppError> {
    let items = sqlx::query_as::<_, InventoryItem>(
        r#"
        SELECT
            id,
            prop_name,
            prop_asset_path,
            layer,
            is_transferable,
            is_portable,
            origin,
            acquired_at
        FROM props.inventory
        WHERE user_id = $1
        ORDER BY acquired_at DESC
        "#,
    )
    .bind(user_id)
    .fetch_all(executor)
    .await?;

    Ok(items)
}

/// Drop a prop (remove from inventory).
pub async fn drop_inventory_item<'e>(
    executor: impl PgExecutor<'e>,
    user_id: Uuid,
    item_id: Uuid,
) -> Result<(), AppError> {
    let result = sqlx::query(
        r#"
        DELETE FROM props.inventory
        WHERE id = $1 AND user_id = $2
        RETURNING id
        "#,
    )
    .bind(item_id)
    .bind(user_id)
    .fetch_optional(executor)
    .await?;

    if result.is_none() {
        return Err(AppError::NotFound(
            "Inventory item not found or not owned by user".to_string(),
        ));
    }

    Ok(())
}
