-- ============================================================================
-- Migration: v62-sinss-credits.sql
-- Sinss Credits virtual currency, cosmetics catalog unlocks, and ledger
-- ============================================================================

-- 1. Add credits balance, avatar_frame, and card_frame to profiles
alter table public.profiles
  add column if not exists credits integer not null default 0 check (credits >= 0);

alter table public.profiles
  add column if not exists avatar_frame text default null;

alter table public.profiles
  add column if not exists card_frame text default null;

-- 2. Credit Transactions Ledger
create table if not exists public.credit_transactions (
  id uuid primary key default gen_random_uuid(),
  user_id uuid not null references auth.users(id) on delete cascade,
  amount integer not null, -- positive for credits earned/bought, negative for spent
  balance_after integer not null,
  action text not null, -- 'welcome_discord', 'view_milestone', 'purchase_pack', 'unlock_cosmetic', 'tip', 'admin_grant'
  description text default '',
  metadata jsonb default '{}'::jsonb,
  created_at timestamptz not null default now()
);

create index if not exists idx_credit_transactions_user_id
  on public.credit_transactions(user_id, created_at desc);

-- 3. Permanent User Unlocks (Cosmetics & Abilities)
create table if not exists public.user_unlocks (
  id uuid primary key default gen_random_uuid(),
  user_id uuid not null references auth.users(id) on delete cascade,
  item_type text not null, -- 'avatar_frame', 'card_frame', 'cursor_trail', 'badge', 'audio_slot', 'alias_slot', 'username_token'
  item_id text not null,
  metadata jsonb default '{}'::jsonb,
  created_at timestamptz not null default now(),
  constraint user_unlocks_unique_item unique(user_id, item_type, item_id)
);

create index if not exists idx_user_unlocks_user_id
  on public.user_unlocks(user_id);

-- Enable RLS
alter table public.credit_transactions enable row level security;
alter table public.user_unlocks enable row level security;

-- Policies for credit_transactions
drop policy if exists "Users can read own credit transactions" on public.credit_transactions;
create policy "Users can read own credit transactions"
  on public.credit_transactions for select
  using (auth.uid() = user_id);

-- Policies for user_unlocks
drop policy if exists "Users can read own unlocks" on public.user_unlocks;
create policy "Users can read own unlocks"
  on public.user_unlocks for select
  using (auth.uid() = user_id);

drop policy if exists "Public can read cosmetic unlocks" on public.user_unlocks;
create policy "Public can read cosmetic unlocks"
  on public.user_unlocks for select
  using (true);

-- 4. Atomic Spend Function
create or replace function public.spend_credits(
  p_user_id uuid,
  p_amount integer,
  p_action text,
  p_description text,
  p_item_type text default null,
  p_item_id text default null
)
returns jsonb
language plpgsql
security definer
set search_path = public
as $$
declare
  v_current_balance integer;
  v_new_balance integer;
begin
  if p_amount <= 0 then
    return jsonb_build_object('success', false, 'error', 'Amount must be greater than zero');
  end if;

  -- Lock row for update
  select credits into v_current_balance
  from public.profiles
  where id = p_user_id
  for update;

  if not found then
    return jsonb_build_object('success', false, 'error', 'Profile not found');
  end if;

  if v_current_balance < p_amount then
    return jsonb_build_object(
      'success', false,
      'error', 'Insufficient credits',
      'current_balance', v_current_balance,
      'required', p_amount
    );
  end if;

  -- Check if already unlocked (if unlockable item)
  if p_item_type is not null and p_item_id is not null then
    if exists (
      select 1 from public.user_unlocks
      where user_id = p_user_id
        and item_type = p_item_type
        and item_id = p_item_id
    ) then
      return jsonb_build_object('success', false, 'error', 'Item already unlocked');
    end if;
  end if;

  v_new_balance := v_current_balance - p_amount;

  -- Deduct from profiles
  update public.profiles
  set credits = v_new_balance
  where id = p_user_id;

  -- Record transaction
  insert into public.credit_transactions (
    user_id,
    amount,
    balance_after,
    action,
    description,
    metadata
  ) values (
    p_user_id,
    -p_amount,
    v_new_balance,
    p_action,
    p_description,
    jsonb_build_object('item_type', p_item_type, 'item_id', p_item_id)
  );

  -- Record unlock if item specified
  if p_item_type is not null and p_item_id is not null then
    insert into public.user_unlocks (user_id, item_type, item_id)
    values (p_user_id, p_item_type, p_item_id)
    on conflict do nothing;
  end if;

  return jsonb_build_object(
    'success', true,
    'new_balance', v_new_balance,
    'spent', p_amount,
    'item_type', p_item_type,
    'item_id', p_item_id
  );
end;
$$;

-- 5. Atomic Grant Function
create or replace function public.grant_credits(
  p_user_id uuid,
  p_amount integer,
  p_action text,
  p_description text,
  p_metadata jsonb default '{}'::jsonb
)
returns jsonb
language plpgsql
security definer
set search_path = public
as $$
declare
  v_current_balance integer;
  v_new_balance integer;
begin
  if p_amount <= 0 then
    return jsonb_build_object('success', false, 'error', 'Amount must be greater than zero');
  end if;

  select credits into v_current_balance
  from public.profiles
  where id = p_user_id
  for update;

  if not found then
    return jsonb_build_object('success', false, 'error', 'Profile not found');
  end if;

  v_new_balance := v_current_balance + p_amount;

  update public.profiles
  set credits = v_new_balance
  where id = p_user_id;

  insert into public.credit_transactions (
    user_id,
    amount,
    balance_after,
    action,
    description,
    metadata
  ) values (
    p_user_id,
    p_amount,
    v_new_balance,
    p_action,
    p_description,
    p_metadata
  );

  return jsonb_build_object(
    'success', true,
    'new_balance', v_new_balance,
    'granted', p_amount
  );
end;
$$;

-- Permissions
revoke all on function public.spend_credits(uuid, integer, text, text, text, text) from public;
grant execute on function public.spend_credits(uuid, integer, text, text, text, text) to authenticated, service_role;

revoke all on function public.grant_credits(uuid, integer, text, text, jsonb) from public;
grant execute on function public.grant_credits(uuid, integer, text, text, jsonb) to service_role;
