-- Add phone field to users tables (public schema + all tenant schemas)
-- phone is nullable, unique when present
-- Also make tenants.admin_email nullable (phone-only registrations have no email)

-- 0. Make tenants.admin_email nullable
ALTER TABLE public.tenants
  ALTER COLUMN admin_email DROP NOT NULL;

-- 1. Public schema users table (auth-service managed, platform admins & default tenant)
ALTER TABLE public.users
  ALTER COLUMN email DROP NOT NULL,
  ADD COLUMN IF NOT EXISTS phone VARCHAR(30) NULL;

-- Partial unique index: only enforce uniqueness when phone is not null
CREATE UNIQUE INDEX IF NOT EXISTS idx_users_phone_unique
  ON public.users (phone) WHERE phone IS NOT NULL;

-- 2. Apply to all existing tenant schemas dynamically
DO $$
DECLARE
  schema_rec RECORD;
BEGIN
  FOR schema_rec IN
    SELECT schema_name
    FROM information_schema.schemata
    WHERE schema_name LIKE 'it0_t_%'
  LOOP
    EXECUTE format(
      'ALTER TABLE %I.users ALTER COLUMN email DROP NOT NULL',
      schema_rec.schema_name
    );
    EXECUTE format(
      'ALTER TABLE %I.users ADD COLUMN IF NOT EXISTS phone VARCHAR(30) NULL',
      schema_rec.schema_name
    );
    EXECUTE format(
      'CREATE UNIQUE INDEX IF NOT EXISTS idx_%s_phone_unique ON %I.users (phone) WHERE phone IS NOT NULL',
      replace(schema_rec.schema_name, 'it0_t_', ''),
      schema_rec.schema_name
    );
  END LOOP;
END;
$$;
