import type { UserAdminEngine } from '@platform-modules/auth';

export class LastAdminError extends Error {
  readonly name = 'LastAdminError';
  constructor(message = 'cannot remove the last active admin') {
    super(message);
  }
}

async function countActiveAdmins(engine: UserAdminEngine): Promise<number> {
  let offset = 0;
  let count = 0;
  while (true) {
    const page = await engine.listUsers({ limit: 200, offset });
    for (const user of page.users) {
      if (user.status === 'active' && user.roles.includes('admin')) {
        count += 1;
      }
    }
    offset += page.users.length;
    if (offset >= page.total || page.users.length === 0) break;
  }
  return count;
}

async function getUser(engine: UserAdminEngine, userId: string) {
  let offset = 0;
  while (true) {
    const page = await engine.listUsers({ limit: 200, offset });
    const found = page.users.find((u) => u.id === userId);
    if (found) return found;
    offset += page.users.length;
    if (offset >= page.total || page.users.length === 0) return null;
  }
}

/** Refuse demoting/disabling the sole remaining active admin (host-side lockout guard). */
export async function assertNotLastAdmin(
  engine: UserAdminEngine,
  userId: string,
  nextRoles?: string[],
): Promise<void> {
  const user = await getUser(engine, userId);
  if (!user || user.status !== 'active' || !user.roles.includes('admin')) return;

  if (nextRoles !== undefined) {
    if (nextRoles.includes('admin')) return;
  }

  const admins = await countActiveAdmins(engine);
  if (admins <= 1) {
    throw new LastAdminError();
  }
}
