-- v46: Let the configured site owner grant permanent stock badges.
-- Run after v45-reserved-special-username.sql.

alter table public.profiles
  add column if not exists admin_badge_ids text[] not null default '{}';

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'
    ]::text[]
  );

create or replace function public.protect_admin_badge_grants()
returns trigger
language plpgsql
set search_path = public
as $$
begin
  if coalesce(auth.role(), '') = 'service_role' then
    return new;
  end if;

  if tg_op = 'INSERT' then
    if cardinality(new.admin_badge_ids) > 0 then
      raise exception 'Permanent badge grants can only be changed by an administrator';
    end if;
  elsif new.admin_badge_ids is distinct from old.admin_badge_ids then
    raise exception 'Permanent badge grants can only be changed by an administrator';
  end if;

  return new;
end;
$$;

drop trigger if exists profiles_protect_admin_badges on public.profiles;
create trigger profiles_protect_admin_badges
  before insert or update on public.profiles
  for each row execute function public.protect_admin_badge_grants();
