-- v86: Allow credit shop badges (coin-collector, stardust, night-owl) and creator/promoter in profiles_admin_badge_ids_allowed
alter table public.profiles
  drop constraint if exists profiles_admin_badge_ids_allowed;

alter table public.profiles
  add constraint profiles_admin_badge_ids_allowed check (
    admin_badge_ids <@ array[
      'owner',
      'staff',
      'helper',
      'verified',
      'premium',
      'donor',
      'og',
      'rich',
      'bug',
      'winner',
      'early',
      'founding100',
      'founding1k',
      'clown',
      'discord-server-booster',
      'halloween-2026',
      'halloween-2026-winner',
      'creator',
      'promoter',
      'coin-collector',
      'stardust',
      'night-owl'
    ]::text[]
  );

-- Backfill admin_badge_ids for all accounts that unlocked badge items in user_unlocks
DO $$
DECLARE
  rec RECORD;
  current_badges text[];
BEGIN
  FOR rec IN
    SELECT user_id, array_agg(DISTINCT item_id) as unlocked_badge_ids
    FROM public.user_unlocks
    WHERE item_type = 'badge'
    GROUP BY user_id
  LOOP
    SELECT COALESCE(admin_badge_ids, ARRAY[]::text[])
    INTO current_badges
    FROM public.profiles
    WHERE id = rec.user_id;

    IF FOUND THEN
      -- Merge unlocked badges into admin_badge_ids
      UPDATE public.profiles
      SET admin_badge_ids = (
        SELECT array_agg(DISTINCT b)
        FROM unnest(current_badges || rec.unlocked_badge_ids) as b
      )
      WHERE id = rec.user_id;
    END IF;
  END LOOP;
END $$;
