-- ============================================================================
-- Migration: v64-avatar-decorations.sql
-- Support equipping Discord Avatar Decorations on user profiles
-- ============================================================================

-- 1. Add avatar_decoration column to public.profiles
alter table public.profiles
  add column if not exists avatar_decoration text default null;

-- 2. Update spend_credits to accept avatar_decoration
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;
$$;
