-- Atomic usage count increment — prevents race conditions on concurrent requests
-- Run this in Supabase SQL Editor AFTER running schema.sql
--
-- Fix B: Tambah parameter p_amount agar usage dihitung per variasi
-- (generate 3 variasi = kurangi 3 kuota, bukan 1)
-- Default p_amount = 1 untuk backward-compatibility.

CREATE OR REPLACE FUNCTION increment_usage_count(p_user_id uuid, p_amount integer DEFAULT 1)
RETURNS void
LANGUAGE sql
SECURITY DEFINER
SET search_path = public
AS $
  UPDATE profiles
  SET
    usage_count = usage_count + p_amount,
    updated_at  = now()
  WHERE id = p_user_id;
$;

-- Allow authenticated users to call this function (only for their own user_id,
-- enforced via RLS on profiles table)
GRANT EXECUTE ON FUNCTION increment_usage_count(uuid, integer) TO authenticated;
