-- Migration: Add username field to users table
-- Date: 2026-05-08
-- Description: Add username column and update phone to be unique for flexible login

-- Add username column
ALTER TABLE "user" ADD COLUMN IF NOT EXISTS username VARCHAR(255);

-- Make phone unique for login purposes (drop constraint first if exists)
DO $$ 
BEGIN
    IF EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'user_phone_key') THEN
        ALTER TABLE "user" DROP CONSTRAINT user_phone_key;
    END IF;
END $$;

-- Add unique constraint on phone (only for non-null values)
CREATE UNIQUE INDEX IF NOT EXISTS idx_user_phone_unique ON "user"(phone) WHERE phone IS NOT NULL;

-- Create unique index on username (only for non-null values)
CREATE UNIQUE INDEX IF NOT EXISTS idx_user_username ON "user"(username) WHERE username IS NOT NULL;

-- Add comments
COMMENT ON COLUMN "user".username IS 'Unique username for login (alternative to email)';
COMMENT ON COLUMN "user".phone IS 'Phone number (can be used for login when provided)';
