-- v72: Secure Global Live Chat (Prevent identity spoofing and unauthorized inserts)
-- 1. Ensure table is in supabase_realtime publication
do $$
begin
  if not exists (
    select 1 from pg_publication_tables 
    where pubname = 'supabase_realtime' and tablename = 'global_chat_messages'
  ) then
    alter publication supabase_realtime add table public.global_chat_messages;
  end if;
end
$$;

-- 2. Full replica identity for realtime delete tracking
alter table public.global_chat_messages replica identity full;

-- 3. Lock down table: remove client-side direct inserts and deletes
drop policy if exists "global_chat_messages_insert" on public.global_chat_messages;
drop policy if exists "global_chat_messages_delete_own" on public.global_chat_messages;

-- 4. Ensure select policy allows clients to receive realtime postgres_changes
drop policy if exists "global_chat_messages_select" on public.global_chat_messages;
create policy "global_chat_messages_select" on public.global_chat_messages
  for select to authenticated, anon
  using (true);

revoke insert, update, delete on public.global_chat_messages from anon, authenticated;
grant select on public.global_chat_messages to anon, authenticated;
