"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.hasGlobalEscalationAccess = void 0;
exports.getVisibleRoles = getVisibleRoles;
exports.validateIds = validateIds;
exports.checkBulkPermission = checkBulkPermission;
exports.resolveAssignee = resolveAssignee;
exports.ensureRoleMembership = ensureRoleMembership;
exports.publishBulkClaimEvents = publishBulkClaimEvents;
const escalationService = __importStar(require("../../services/escalation"));
const userService = __importStar(require("../../services/user"));
const publish_1 = require("../../lib/events/publish");
// ── Private helpers ────────────────────────────────────────────────────────
// Re-export from service layer for use by escalation API modules
var user_1 = require("../../services/user");
Object.defineProperty(exports, "hasGlobalEscalationAccess", { enumerable: true, get: function () { return user_1.hasGlobalEscalationAccess; } });
async function getVisibleRoles(userId) {
    if (await userService.hasGlobalEscalationAccess(userId))
        return undefined;
    const userRoles = await userService.getUserRoles(userId);
    return userRoles.map((r) => r.role);
}
function validateIds(ids) {
    return Array.isArray(ids) && ids.length > 0;
}
async function checkBulkPermission(userId, ids) {
    if (await userService.hasGlobalEscalationAccess(userId))
        return { allowed: true };
    const roles = await escalationService.getEscalationRoles(ids);
    if (!roles.length)
        return { allowed: true };
    // Single batched query instead of N+1 loop
    const canManageAll = await userService.hasRolesAsAdmin(userId, roles);
    if (!canManageAll) {
        return { allowed: false, status: 403, error: 'Insufficient permissions for one or more escalation roles' };
    }
    return { allowed: true };
}
/**
 * Resolve an optional assignee external_id to an internal userId.
 * When omitted, returns the caller's userId from auth.
 *
 * When `provisionIfAbsent` is provided and the caller has global access,
 * the user is JIT-provisioned if absent and roles are ensured. This avoids
 * pre-flight queries — the happy path (user exists) is one lookup.
 */
async function resolveAssignee(assignee, auth, provisionIfAbsent) {
    if (!assignee)
        return { userId: auth.userId };
    // Happy path: user exists
    const user = await userService.getUserByExternalId(assignee);
    if (user)
        return { userId: user.id };
    // User not found — provision if caller has authority and flag is set
    if (!provisionIfAbsent) {
        return { error: { status: 404, error: `User not found for external_id: ${assignee}` } };
    }
    const hasAuthority = await userService.hasGlobalEscalationAccess(auth.userId);
    if (!hasAuthority) {
        return { error: { status: 403, error: 'Only superadmin or admin can provision users on claim' } };
    }
    // Provision the user
    const created = await userService.createUser({
        external_id: assignee,
        display_name: provisionIfAbsent.displayName || assignee,
        email: provisionIfAbsent.email,
        roles: (provisionIfAbsent.roles || []).map((r) => ({
            role: r.role,
            type: (r.type || 'member'),
        })),
    });
    return { userId: created.id };
}
/**
 * Ensure a user has the required role for an escalation.
 * Called after claim when the atomic SQL returns null due to role mismatch.
 * Only adds the role if `provisionIfAbsent` declares it and caller has authority.
 */
async function ensureRoleMembership(userId, requiredRole, callerUserId, provisionIfAbsent) {
    if (!provisionIfAbsent)
        return false;
    const hasAuthority = await userService.hasGlobalEscalationAccess(callerUserId);
    if (!hasAuthority)
        return false;
    // Check if the provision declares this role
    const declaredRole = provisionIfAbsent.roles?.find((r) => r.role === requiredRole);
    if (!declaredRole)
        return false;
    // Add the role — idempotent (ON CONFLICT DO NOTHING)
    try {
        await userService.addUserRole(userId, requiredRole, (declaredRole.type || 'member'));
    }
    catch { /* already has it */ }
    return true;
}
function publishBulkClaimEvents(ids, assignedTo) {
    for (const id of ids) {
        (0, publish_1.publishEscalationEvent)({
            type: 'escalation.claimed',
            source: 'api',
            workflowId: '',
            workflowName: '',
            taskQueue: '',
            escalationId: id,
            status: 'claimed',
            data: { assigned_to: assignedTo, bulk: true },
        });
    }
}
