-- 2026-02-28: cleanup duplicates and enforce device_id NOT NULL
-- 1) Deduplicate rows keeping the newest by created_at
WITH ranked AS (
  SELECT id, ROW_NUMBER() OVER (PARTITION BY token, user_id ORDER BY created_at DESC) rn
  FROM public.fcm_tokens
)
DELETE FROM public.fcm_tokens
WHERE id IN (SELECT id FROM ranked WHERE rn > 1);

-- 2) Ensure device_id is populated for any legacy rows
UPDATE public.fcm_tokens
SET device_id = gen_random_uuid()::text
WHERE device_id IS NULL;

-- 3) Enforce NOT NULL on device_id
ALTER TABLE public.fcm_tokens
ALTER COLUMN device_id SET NOT NULL;

-- 4) Ensure unique index on (user_id, device_id) exists
CREATE UNIQUE INDEX IF NOT EXISTS fcm_tokens_user_device_idx
  ON public.fcm_tokens(user_id, device_id);

-- 5) (Optional) keep a normal index on user_id for queries
CREATE INDEX IF NOT EXISTS fcm_tokens_user_idx ON public.fcm_tokens(user_id);
