-- V010: Add Multi-Factor Authentication (MFA) fields to users table
-- Created: 2025-10-01
-- Description: Adds support for TOTP (Google Authenticator) and Email MFA

-- Add MFA fields to users table
ALTER TABLE users ADD COLUMN IF NOT EXISTS mfa_enabled BOOLEAN DEFAULT false NOT NULL;
ALTER TABLE users ADD COLUMN IF NOT EXISTS mfa_method VARCHAR(20);
ALTER TABLE users ADD COLUMN IF NOT EXISTS totp_secret VARCHAR(32);
ALTER TABLE users ADD COLUMN IF NOT EXISTS mfa_backup_codes JSONB;
ALTER TABLE users ADD COLUMN IF NOT EXISTS email_mfa_code VARCHAR(6);
ALTER TABLE users ADD COLUMN IF NOT EXISTS email_mfa_code_expires_at TIMESTAMP WITHOUT TIME ZONE;

-- Add index for MFA queries
CREATE INDEX IF NOT EXISTS idx_users_mfa_enabled ON users(mfa_enabled) WHERE mfa_enabled = true;

-- Comments
COMMENT ON COLUMN users.mfa_enabled IS 'Whether MFA is enabled for this user';
COMMENT ON COLUMN users.mfa_method IS 'MFA method: totp (Google Authenticator) or email';
COMMENT ON COLUMN users.totp_secret IS 'Encrypted TOTP secret for Google Authenticator';
COMMENT ON COLUMN users.mfa_backup_codes IS 'Array of backup codes (hashed) for MFA recovery';
COMMENT ON COLUMN users.email_mfa_code IS 'Temporary email verification code for email-based MFA';
COMMENT ON COLUMN users.email_mfa_code_expires_at IS 'Expiration time for email MFA code (5 minutes)';
