"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ssoProvision = ssoProvision;
const logger_1 = require("../../lib/logger");
const crud_1 = require("./crud");
const roles_1 = require("./roles");
/**
 * JIT provision or sync an SSO identity to lt_users.
 *
 * Lookup by `external_id`. If not found, create with resolved roles.
 * If found, sync any new roles from the identity.
 *
 * Returns the internal `lt_users.id` (UUID) that all RBAC and
 * escalation queries use.
 */
async function ssoProvision(identity, ssoConfig) {
    const defaultRoleType = ssoConfig.defaultRoleType || 'member';
    const ltRoles = resolveRoles(identity.roles || [], defaultRoleType, ssoConfig.roleMap);
    const existing = await (0, crud_1.getUserByExternalId)(identity.externalId);
    if (existing) {
        // Sync roles: ensure all resolved roles exist on the user
        const currentRoles = await (0, roles_1.getUserRoles)(existing.id);
        for (const lr of ltRoles) {
            const has = currentRoles.some((r) => r.role === lr.role);
            if (!has) {
                await (0, roles_1.addUserRole)(existing.id, lr.role, lr.type);
            }
        }
        const updatedRoles = await (0, roles_1.getUserRoles)(existing.id);
        return {
            userId: existing.id,
            roles: updatedRoles.map((r) => ({ role: r.role, type: r.type })),
            created: false,
        };
    }
    // Create new user
    const user = await (0, crud_1.createUser)({
        external_id: identity.externalId,
        email: identity.email || undefined,
        display_name: identity.displayName || identity.externalId,
        roles: ltRoles.map((r) => ({ role: r.role, type: r.type })),
        metadata: identity.metadata,
    });
    logger_1.loggerRegistry.info(`[lt-sso] provisioned user: ${identity.externalId} → ${user.id}`);
    return {
        userId: user.id,
        roles: (user.roles || []).map((r) => ({ role: r.role, type: r.type })),
        created: true,
    };
}
function resolveRoles(hostRoles, defaultRoleType, roleMap) {
    const mapped = roleMap
        ? hostRoles.filter((r) => roleMap[r]).map((r) => roleMap[r])
        : hostRoles;
    if (mapped.length === 0) {
        return [{ role: defaultRoleType, type: defaultRoleType }];
    }
    return mapped.map((role) => ({
        role,
        type: role === 'superadmin' ? 'superadmin' : role === 'admin' ? 'admin' : 'member',
    }));
}
