-- ============================================
-- Migration: Fix devices table unique constraint
-- Purpose: Change from global unique name to per-user unique name
-- Run this in Supabase SQL Editor
-- ============================================

-- Step 1: Drop the old unique constraint on 'name' only
ALTER TABLE public.devices DROP CONSTRAINT IF EXISTS devices_name_key;

-- Step 2: Add composite unique constraint on (user_id, name)
-- This ensures device names are unique per user, not globally
ALTER TABLE public.devices ADD CONSTRAINT devices_user_id_name_key UNIQUE (user_id, name);

-- Verify the constraint was added
SELECT
    conname AS constraint_name,
    pg_get_constraintdef(oid) AS constraint_definition
FROM pg_constraint
WHERE conrelid = 'public.devices'::regclass
  AND contype = 'u';
