//! AI usage billing helper for room service.
//!
//! Delegates to `agent::billing::record_ai_usage`.
//! Billing is non-fatal — failures are logged but do not block AI responses.

use db::database::AppDatabase;
use uuid::Uuid;

use crate::error::RoomError;

/// Record AI token usage against a project's billing balance.
///
/// Returns `Ok(())` on success. On billing failure (e.g. insufficient balance,
/// missing pricing), returns `Err` but the caller should still complete the AI
/// request — billing is a non-critical side-effect.
pub async fn record_ai_usage(
    db: &AppDatabase,
    project_id: Uuid,
    model_id: Uuid,
    input_tokens: i64,
    output_tokens: i64,
) -> Result<(), RoomError> {
    if input_tokens == 0 && output_tokens == 0 {
        return Ok(());
    }

    match agent::billing::record_ai_usage(db, project_id, model_id, input_tokens, output_tokens).await {
        Ok(record) => {
            tracing::info!(
                project_id = %project_id,
                model_id = %model_id,
                input_tokens = input_tokens,
                output_tokens = output_tokens,
                cost_usd = %record.cost,
                "ai_usage_recorded"
            );
            Ok(())
        }
        Err(e) => {
            tracing::warn!(
                project_id = %project_id,
                model_id = %model_id,
                input_tokens = input_tokens,
                output_tokens = output_tokens,
                error = %e,
                "ai_billing_failed_non_fatal"
            );
            Err(e.into())
        }
    }
}
