-- add device_id column to fcm_tokens and a unique constraint on (user_id, device_id)

alter table if exists public.fcm_tokens
  add column if not exists device_id text;

-- create a unique index so upsert can update the row for the same device
create unique index if not exists fcm_tokens_user_device_idx
  on public.fcm_tokens(user_id, device_id);

-- ensure device_id is protected by RLS policies: allow users to insert/update/delete their device rows
-- (these policies assume RLS is already enabled on the table)
create policy if not exists "Allow users insert their device tokens" on public.fcm_tokens
  for insert with check (auth.uid() = user_id);

create policy if not exists "Allow users delete their device tokens" on public.fcm_tokens
  for delete using (auth.uid() = user_id);

create policy if not exists "Allow users update their device tokens" on public.fcm_tokens
  for update using (auth.uid() = user_id) with check (auth.uid() = user_id);
