use sqlx::PgPool;

/// Reset daily_actions_used for all subscriptions every day.
#[allow(dead_code)]
pub async fn reset_daily_actions(pool: &PgPool) -> Result<(), sqlx::Error> {
    let rows = sqlx::query(
        "UPDATE user_ai_subscriptions SET daily_actions_used = 0, updated_at = NOW()"
    )
    .execute(pool)
    .await?
    .rows_affected();

    tracing::info!("Reset daily_actions_used for {} AI subscriptions", rows);
    Ok(())
}

/// Reset monthly credits at the start of each billing period. This is a
/// conservative implementation that resets credits for any subscription whose
/// current_period_end has passed, and rolls the period forward by one month.
pub async fn reset_monthly_credits(pool: &PgPool) -> Result<(), sqlx::Error> {
    let now = chrono::Utc::now();

    let rows = sqlx::query(
        r#"
        UPDATE user_ai_subscriptions
        SET monthly_credits_used = 0,
            daily_actions_used = 0,
            current_period_start = current_period_end,
            current_period_end = current_period_end + INTERVAL '1 month',
            updated_at = NOW()
        WHERE current_period_end <= $1
        "#
    )
    .bind(now)
    .execute(pool)
    .await?
    .rows_affected();

    tracing::info!("Rolled monthly credits for {} AI subscriptions", rows);
    Ok(())
}
