globalThis.process ??= {};
globalThis.process.env ??= {};
//#region src/lib/user-admin.ts
var LastAdminError = class extends Error {
	name = "LastAdminError";
	constructor(message = "cannot remove the last active admin") {
		super(message);
	}
};
async function countActiveAdmins(engine) {
	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, userId) {
	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). */
async function assertNotLastAdmin(engine, userId, nextRoles) {
	const user = await getUser(engine, userId);
	if (!user || user.status !== "active" || !user.roles.includes("admin")) return;
	if (nextRoles !== void 0) {
		if (nextRoles.includes("admin")) return;
	}
	if (await countActiveAdmins(engine) <= 1) throw new LastAdminError();
}
//#endregion
export { assertNotLastAdmin as t };
