-- v58: Global Community Live Chat (Shoutbox)
create table if not exists public.global_chat_messages (
  id uuid primary key default gen_random_uuid(),
  user_id uuid not null references public.profiles(id) on delete cascade,
  username text not null,
  avatar_url text,
  is_premium boolean not null default false,
  message text not null,
  created_at timestamptz not null default now()
);

create index if not exists idx_global_chat_messages_created_at on public.global_chat_messages(created_at desc);

alter table public.global_chat_messages enable row level security;

-- Everyone can read messages
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);

-- Authenticated users can insert their own message
drop policy if exists "global_chat_messages_insert" on public.global_chat_messages;
create policy "global_chat_messages_insert" on public.global_chat_messages
  for insert to authenticated
  with check (auth.uid() = user_id);

-- Users can delete their own message
drop policy if exists "global_chat_messages_delete_own" on public.global_chat_messages;
create policy "global_chat_messages_delete_own" on public.global_chat_messages
  for delete to authenticated
  using (auth.uid() = user_id);
