"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.seedAdmin = seedAdmin;
const logger_1 = require("../../lib/logger");
const role_1 = require("../role");
const crud_1 = require("./crud");
const roles_1 = require("./roles");
/**
 * Seed a superadmin user. Idempotent — skips creation if the user
 * already exists, but ensures the superadmin role is present.
 *
 * Returns the user's UUID so callers can pass it to `createClient()`.
 */
async function seedAdmin(input) {
    const { externalId, displayName, email, password } = input;
    // Ensure the superadmin role exists
    try {
        await (0, role_1.createRole)('superadmin');
    }
    catch { /* ON CONFLICT DO NOTHING */ }
    const existing = await (0, crud_1.getUserByExternalId)(externalId);
    if (existing) {
        // Ensure existing user has the superadmin role
        const roles = await (0, roles_1.getUserRoles)(existing.id);
        const hasSuperadmin = roles.some((r) => r.role === 'superadmin' && r.type === 'superadmin');
        if (!hasSuperadmin) {
            await (0, roles_1.addUserRole)(existing.id, 'superadmin', 'superadmin');
            logger_1.loggerRegistry.info(`[seed-admin] granted superadmin role to ${externalId}`);
        }
        logger_1.loggerRegistry.info(`[seed-admin] ${externalId} already exists, skipping creation`);
        return existing.id;
    }
    const user = await (0, crud_1.createUser)({
        external_id: externalId,
        email: email || undefined,
        display_name: displayName || externalId,
        password: password || undefined,
        roles: [{ role: 'superadmin', type: 'superadmin' }],
    });
    logger_1.loggerRegistry.info(`[seed-admin] created superadmin user: ${externalId}`);
    return user.id;
}
