-- Migration script: Replace sequential user IDs with UUIDs for security
-- This prevents enumeration attacks and improves security

-- Step 1: Enable UUID extension if not already enabled
CREATE EXTENSION IF NOT EXISTS "uuid-ossp";

-- Step 2: Add new UUID column to users table
ALTER TABLE users ADD COLUMN uuid_id UUID DEFAULT uuid_generate_v4();

-- Step 3: Update all existing users to have UUIDs (they will be auto-generated)
UPDATE users SET uuid_id = uuid_generate_v4() WHERE uuid_id IS NULL;

-- Step 4: Make UUID column NOT NULL
ALTER TABLE users ALTER COLUMN uuid_id SET NOT NULL;

-- Step 5: Add new UUID column to user_evaluations table
ALTER TABLE user_evaluations ADD COLUMN user_uuid UUID;

-- Step 6: Update user_evaluations to use the new UUIDs
UPDATE user_evaluations 
SET user_uuid = users.uuid_id 
FROM users 
WHERE user_evaluations.user_id = users.id;

-- Step 7: Make user_uuid NOT NULL
ALTER TABLE user_evaluations ALTER COLUMN user_uuid SET NOT NULL;

-- Step 8: Add new UUID column to skill_evaluations (via user_evaluations)
-- No direct change needed as skill_evaluations references user_evaluations.id

-- Step 9: Create unique constraint on UUID
ALTER TABLE users ADD CONSTRAINT users_uuid_unique UNIQUE (uuid_id);

-- Step 10: Add unique constraint and foreign key for user_evaluations
ALTER TABLE user_evaluations ADD CONSTRAINT user_evaluations_user_uuid_unique UNIQUE (user_uuid);
ALTER TABLE user_evaluations ADD CONSTRAINT fk_user_evaluations_user_uuid 
    FOREIGN KEY (user_uuid) REFERENCES users(uuid_id);

-- Note: The actual switchover will be done in the application code
-- The old id columns will be kept temporarily for backward compatibility
