-- Migration: Add Rejection Fields to Users Table
-- Description: Adds rejection tracking fields and rejected status to UserStatus enum
-- Date: 2025-12-18

BEGIN;

-- Add 'rejected' value to UserStatus enum if it doesn't exist
DO $$
BEGIN
    IF NOT EXISTS (
        SELECT 1 FROM pg_enum
        WHERE enumlabel = 'rejected'
        AND enumtypid = (SELECT oid FROM pg_type WHERE typname = 'userstatus')
    ) THEN
        ALTER TYPE userstatus ADD VALUE 'rejected';
        RAISE NOTICE 'Added rejected to userstatus enum';
    ELSE
        RAISE NOTICE 'rejected already exists in userstatus enum';
    END IF;
END$$;

-- Add rejection tracking fields to users table
ALTER TABLE users
ADD COLUMN IF NOT EXISTS rejection_reason TEXT,
ADD COLUMN IF NOT EXISTS rejected_at TIMESTAMP WITH TIME ZONE,
ADD COLUMN IF NOT EXISTS rejected_by UUID REFERENCES users(id);

-- Add comments for documentation
COMMENT ON COLUMN users.rejection_reason IS 'Reason provided when application was rejected';
COMMENT ON COLUMN users.rejected_at IS 'Timestamp when application was rejected';
COMMENT ON COLUMN users.rejected_by IS 'Admin who rejected the application';

-- Create index on rejected_at for filtering rejected users
CREATE INDEX IF NOT EXISTS idx_users_rejected_at ON users(rejected_at) WHERE rejected_at IS NOT NULL;

COMMIT;

-- Verify migration
SELECT 'Rejection fields added successfully' AS status;
SELECT COUNT(*) AS rejected_users_count FROM users WHERE status = 'rejected';
