/**
 * usage-quota.ts — Atomic usage quota helper
 *
 * Gunakan checkAndIncrementUsage() sebagai pengganti pola
 * read-check-write di setiap API route.
 *
 * Pola lama (RACE CONDITION):
 *   const profile = await select usage_count ...
 *   if (profile.usage_count >= profile.usage_limit) return 403
 *   await rpc("increment_usage_count", ...)
 *
 * Pola baru (ATOMIC via DB lock):
 *   const result = await checkAndIncrementUsage(supabase, userId, amount)
 *   if (result === "quota_exceeded") return 403
 */

import type { SupabaseClient } from "@supabase/supabase-js";

export type UsageCheckResult =
  | "ok"              // diizinkan, sudah di-increment
  | "reset"           // quota direset (bulan baru), diizinkan
  | "quota_exceeded"  // kuota habis
  | "not_found"       // profil tidak ditemukan
  | "error";          // DB error (fallback: allow)

/**
 * Check and atomically increment usage via DB-level row lock.
 * Tidak ada race condition antar concurrent requests.
 *
 * @param supabase  Server-side Supabase client
 * @param userId    User UUID
 * @param amount    Jumlah yang di-increment (default 1)
 */
export async function checkAndIncrementUsage(
  supabase: SupabaseClient,
  userId: string,
  amount = 1
): Promise<UsageCheckResult> {
  try {
    const { data, error } = await supabase
      .rpc("check_and_increment_usage", {
        p_user_id: userId,
        p_amount: amount,
      });

    if (error) {
      console.error("[usage-quota] RPC error:", error.message);
      // Fail open — jangan block user karena DB error
      return "error";
    }

    return (data as UsageCheckResult) ?? "error";
  } catch (e) {
    console.error("[usage-quota] Unexpected error:", e);
    return "error";
  }
}
