-- Add device_id column to fcm_tokens
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);

-- Drop policies if they exist to prevent duplication errors
drop policy if exists "Allow users insert their device tokens" on public.fcm_tokens;
drop policy if exists "Allow users delete their device tokens" on public.fcm_tokens;
drop policy if exists "Allow users update their device tokens" on public.fcm_tokens;

-- Recreate the RLS policies
create policy "Allow users insert their device tokens" on public.fcm_tokens
  for insert with check (auth.uid() = user_id);

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

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