-- 002_ci_username.sql
-- Case-insensitive unique indexes for username and email.
-- Replaces the default UNIQUE constraint (which is case-sensitive).

-- Normalize existing rows to lowercase first
UPDATE users SET username = LOWER(username) WHERE username != LOWER(username);
UPDATE users SET email = LOWER(email) WHERE email != LOWER(email);

-- Drop old case-sensitive unique constraints and add case-insensitive indexes
ALTER TABLE users DROP CONSTRAINT IF EXISTS users_username_key;
ALTER TABLE users DROP CONSTRAINT IF EXISTS users_email_key;

CREATE UNIQUE INDEX IF NOT EXISTS users_username_ci ON users (LOWER(username));
CREATE UNIQUE INDEX IF NOT EXISTS users_email_ci ON users (LOWER(email));
