"use strict";
/**
 * Resolve an LTEnvelopePrincipal from external_id or UUID in a single query.
 *
 * Called at the front door (API routes, cron) — never inside workflows.
 * Uses a LEFT JOIN to fetch user + roles in one round-trip.
 *
 * Accepts either:
 * - external_id (e.g., 'superadmin', 'lt-system')
 * - UUID id (e.g., '76d28d6c-...' — as stored in JWT userId)
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.resolvePrincipal = resolvePrincipal;
const db_1 = require("../../lib/db");
const sql_1 = require("./sql");
/** UUID v4 pattern for distinguishing UUIDs from external_ids. */
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
const ROLE_TYPE_PRIORITY = { superadmin: 3, admin: 2, member: 1 };
async function resolvePrincipal(identifier) {
    const pool = (0, db_1.getPool)();
    const { rows } = await pool.query(sql_1.GET_USER_WITH_ROLES_FLEXIBLE, [identifier]);
    if (rows.length === 0)
        return null;
    const user = rows[0];
    const roleNames = [];
    let highestPriority = 0;
    let highestType;
    for (const row of rows) {
        if (row.role) {
            roleNames.push(row.role);
            const priority = ROLE_TYPE_PRIORITY[row.role_type] ?? 0;
            if (priority > highestPriority) {
                highestPriority = priority;
                highestType = row.role_type;
            }
        }
    }
    // Use external_id as the canonical identifier (stable, human-readable)
    return {
        id: user.external_id,
        type: user.metadata?.account_type ?? 'user',
        displayName: user.display_name ?? undefined,
        roles: roleNames,
        roleType: highestType,
    };
}
