"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.createEscalation = createEscalation;
const escalationService = __importStar(require("../../services/escalation"));
const userService = __importStar(require("../../services/user"));
const publish_1 = require("../../lib/events/publish");
// ── Create ────────────────────────────────────────────────────────────────
/**
 * Create a standalone escalation (not tied to a workflow).
 *
 * Useful for manual work items, support tickets, or approval requests
 * that originate outside the durable workflow engine. The caller must
 * hold the target role or be a superadmin.
 *
 * @param input.type — escalation category (e.g. `"support"`, `"approval"`)
 * @param input.subtype — subcategory for finer routing
 * @param input.role — role responsible for resolving this escalation
 * @param input.description — human-readable summary
 * @param input.priority — 1 (critical) through 4 (low), default 2
 * @param input.envelope — serialized context for the resolver
 * @param input.metadata — arbitrary key-value data (e.g. signal_routing)
 * @param input.escalation_payload — serialized payload for the resolver UI
 * @param auth — authenticated user context (must hold target role or be superadmin)
 * @returns `{ status: 201, data: <escalation record> }`
 */
async function createEscalation(input, auth) {
    try {
        const { type, role } = input;
        if (!type || typeof type !== 'string') {
            return { status: 400, error: 'type is required' };
        }
        if (!role || typeof role !== 'string') {
            return { status: 400, error: 'role is required' };
        }
        // RBAC: caller must hold the target role or be superadmin
        const isSuperAdminUser = await userService.isSuperAdmin(auth.userId);
        if (!isSuperAdminUser) {
            const userHasRole = await userService.hasRole(auth.userId, role);
            if (!userHasRole) {
                return { status: 403, error: `You must hold the "${role}" role or be a superadmin to create escalations for it` };
            }
        }
        const escalation = await escalationService.createEscalation({
            type,
            subtype: input.subtype ?? type,
            description: input.description,
            priority: input.priority,
            role,
            envelope: input.envelope ?? '{}',
            metadata: input.metadata,
            escalation_payload: input.escalation_payload,
        });
        (0, publish_1.publishEscalationEvent)({
            type: 'escalation.created',
            source: 'api',
            workflowId: '',
            workflowName: '',
            taskQueue: '',
            escalationId: escalation.id,
            status: 'pending',
            data: { type: input.type, role },
        });
        return { status: 201, data: escalation };
    }
    catch (err) {
        return { status: 500, error: err.message };
    }
}
