-- Add foreign key relationship between consulting_slots and profiles (user_id)
-- This enables the relationship query in ConsultingHistory component

-- First, check if the foreign key already exists
DO $$
BEGIN
    IF NOT EXISTS (
        SELECT 1 FROM information_schema.table_constraints
        WHERE table_name = 'consulting_slots'
        AND constraint_name = 'consulting_slots_user_id_fkey'
    ) THEN
        -- Add foreign key constraint if it doesn't exist
        ALTER TABLE consulting_slots
        ADD CONSTRAINT consulting_slots_user_id_fkey
        FOREIGN KEY (user_id) REFERENCES auth.users(id) ON DELETE CASCADE;

        RAISE NOTICE 'Foreign key constraint added for user_id';
    ELSE
        RAISE NOTICE 'Foreign key constraint for user_id already exists';
    END IF;
END $$;

-- Verify the relationship
SELECT
    tc.table_name,
    kcu.column_name,
    ccu.table_name AS foreign_table_name,
    ccu.column_name AS foreign_column_name
FROM information_schema.table_constraints AS tc
JOIN information_schema.key_column_usage AS kcu
    ON tc.constraint_name = kcu.constraint_name
    AND tc.table_schema = kcu.table_schema
JOIN information_schema.constraint_column_usage AS ccu
    ON ccu.constraint_name = tc.constraint_name
WHERE tc.constraint_type = 'FOREIGN KEY'
AND tc.table_name = 'consulting_slots'
AND kcu.column_name = 'user_id';
