DO $$
BEGIN
  IF to_regclass('public.tenants') IS NULL THEN
    RAISE EXCEPTION 'missing table: tenants';
  END IF;
  IF to_regclass('public.users') IS NULL THEN
    RAISE EXCEPTION 'missing table: users';
  END IF;
  IF to_regclass('public.roles') IS NULL THEN
    RAISE EXCEPTION 'missing table: roles';
  END IF;
  IF to_regclass('public.permissions') IS NULL THEN
    RAISE EXCEPTION 'missing table: permissions';
  END IF;
  IF to_regclass('public.user_roles') IS NULL THEN
    RAISE EXCEPTION 'missing table: user_roles';
  END IF;
  IF to_regclass('public.role_permissions') IS NULL THEN
    RAISE EXCEPTION 'missing table: role_permissions';
  END IF;
  IF to_regclass('public.refresh_tokens') IS NULL THEN
    RAISE EXCEPTION 'missing table: refresh_tokens';
  END IF;
  IF to_regclass('public.audit_logs') IS NULL THEN
    RAISE EXCEPTION 'missing table: audit_logs';
  END IF;

  IF NOT EXISTS (
    SELECT 1 FROM information_schema.columns
    WHERE table_schema = 'public' AND table_name = 'tenants' AND column_name = 'status'
  ) THEN
    RAISE EXCEPTION 'tenants.status missing';
  END IF;
  IF NOT EXISTS (
    SELECT 1 FROM information_schema.columns
    WHERE table_schema = 'public' AND table_name = 'tenants' AND column_name = 'config'
  ) THEN
    RAISE EXCEPTION 'tenants.config missing';
  END IF;
  IF NOT EXISTS (
    SELECT 1 FROM information_schema.columns
    WHERE table_schema = 'public' AND table_name = 'users' AND column_name = 'mfa_enabled'
  ) THEN
    RAISE EXCEPTION 'users.mfa_enabled missing';
  END IF;

  IF NOT EXISTS (
    SELECT 1
    FROM pg_indexes
    WHERE schemaname = 'public' AND tablename = 'users' AND indexname = 'idx_users_tenant_email'
  ) THEN
    RAISE EXCEPTION 'missing index: idx_users_tenant_email';
  END IF;

  IF NOT EXISTS (
    SELECT 1
    FROM pg_constraint c
    JOIN pg_class t ON t.oid = c.conrelid
    WHERE t.relname = 'users' AND c.contype = 'f' AND pg_get_constraintdef(c.oid) LIKE 'FOREIGN KEY (tenant_id)%'
  ) THEN
    RAISE EXCEPTION 'missing foreign key users.tenant_id -> tenants.id';
  END IF;

  IF NOT EXISTS (
    SELECT 1 FROM tenants WHERE id = '11111111-1111-1111-1111-111111111111'
  ) THEN
    RAISE EXCEPTION 'missing seed tenant Default Corp';
  END IF;

  IF NOT EXISTS (SELECT 1 FROM permissions WHERE code = 'user:read') THEN
    RAISE EXCEPTION 'missing seed permission user:read';
  END IF;
END $$;

