-- ============================================================
-- 002_admin_users_self_service.sql
-- Phase 2: Domain-Admin support.
--
-- The admin_users table already has all required columns from 001_init.sql:
--   - role TEXT NOT NULL DEFAULT 'super_admin'
--   - allowed_domains TEXT[] NOT NULL DEFAULT '{}'
--   - active BOOLEAN NOT NULL DEFAULT true
--
-- This migration just adds a check constraint on role and an index
-- for fast role/active lookups.
-- ============================================================

-- Drop any old/legacy variants of the constraint to make this migration
-- idempotent across environments.
ALTER TABLE admin_users DROP CONSTRAINT IF EXISTS admin_users_role_chk;
ALTER TABLE admin_users DROP CONSTRAINT IF EXISTS admin_users_role_check;

-- Reapply the canonical check constraint.
ALTER TABLE admin_users
  ADD CONSTRAINT admin_users_role_check
  CHECK (role IN ('super_admin', 'domain_admin'));

-- Useful index for role-based filtering.
CREATE INDEX IF NOT EXISTS idx_admin_users_role_active
  ON admin_users(role, active);
