-- v36: route profile writes through the server and protect Discord identity metadata.
drop policy if exists "profiles_update_own" on public.profiles;

alter table public.profiles
  add column if not exists discord_premium_type smallint not null default 0;

create or replace function public.protect_profile_discord_link_fields()
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 coalesce(new.discord_id, '') <> '' or coalesce(new.discord_premium_type, 0) <> 0 then
      raise exception 'Discord account metadata must be set through Discord linking';
    end if;
  elsif new.discord_id is distinct from old.discord_id
     or coalesce(new.discord_premium_type, 0) is distinct from coalesce(old.discord_premium_type, 0) then
    raise exception 'Discord account metadata must be set through Discord linking';
  end if;

  return new;
end;
$$;

drop trigger if exists profiles_protect_discord_link_fields on public.profiles;
create trigger profiles_protect_discord_link_fields
  before insert or update on public.profiles
  for each row execute function public.protect_profile_discord_link_fields();

alter table public.app_owners enable row level security;
drop policy if exists "app_owners_public_read" on public.app_owners;
revoke all on public.app_owners from anon, authenticated;