"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.invokeWorkflow = invokeWorkflow;
exports.getWorkflowStatus = getWorkflowStatus;
exports.getWorkflowResult = getWorkflowResult;
exports.terminateWorkflow = terminateWorkflow;
exports.exportWorkflow = exportWorkflow;
const workers_1 = require("../../workers");
const exportService = __importStar(require("../../services/export"));
const task_1 = require("../../services/task");
const workflow_invocation_1 = require("../../services/workflow-invocation");
function isResolveError(err) {
    return err?.message?.includes('Cannot resolve workflow');
}
/**
 * Start a workflow — proxy for `Durable.Client.workflow.start()`.
 *
 * Resolves the task queue, enforces auth/role constraints, builds the
 * LTEnvelope with IAM context, and delegates to the Durable client.
 * Any WorkflowOptions field (workflowId, expire, entity, namespace,
 * search, signalIn, pending, etc.) can be passed via `options` and
 * flows through to the Durable client unchanged.
 *
 * @see https://docs.hotmesh.io/types/types_durable.WorkflowOptions.html
 */
async function invokeWorkflow(input, auth) {
    try {
        await (0, workflow_invocation_1.checkInvocationRoles)(input.type, auth.userId, auth.role);
        const result = await (0, workflow_invocation_1.invokeWorkflow)({
            workflowType: input.type,
            data: input.data || {},
            metadata: input.metadata,
            executeAs: input.execute_as,
            options: input.options,
            auth: {
                userId: auth.userId,
                role: auth.role,
                scopes: auth.scopes,
            },
        });
        return {
            status: 202,
            data: { workflowId: result.workflowId, message: 'Workflow started' },
        };
    }
    catch (err) {
        const status = err instanceof workflow_invocation_1.InvocationError ? err.statusCode : 500;
        return { status, error: err.message };
    }
}
/**
 * Get the execution status of a workflow.
 *
 * Returns the HotMesh status code (0 = completed, 1 = running).
 * Resolves the workflow handle via task record or worker registry.
 *
 * @param input.workflowId — HotMesh workflow ID
 * @returns `{ status: 200, data: { workflowId, status } }` or 404
 */
async function getWorkflowStatus(input) {
    try {
        const resolved = await (0, task_1.resolveWorkflowHandle)(input.workflowId);
        const client = (0, workers_1.createClient)();
        const handle = await client.workflow.getHandle(resolved.taskQueue, resolved.workflowName, input.workflowId);
        const status = await handle.status();
        return {
            status: 200,
            data: { workflowId: input.workflowId, status },
        };
    }
    catch (err) {
        if (isResolveError(err))
            return { status: 404, error: err.message };
        return { status: 500, error: err.message };
    }
}
/**
 * Get the result of a completed workflow.
 *
 * Returns 202 if the workflow is still running, 200 with the result
 * payload when complete. Never blocks — always returns immediately.
 *
 * @param input.workflowId — HotMesh workflow ID
 * @returns `{ status: 200, data: { workflowId, result } }` or 202 if running
 */
async function getWorkflowResult(input) {
    try {
        const resolved = await (0, task_1.resolveWorkflowHandle)(input.workflowId);
        const client = (0, workers_1.createClient)();
        const handle = await client.workflow.getHandle(resolved.taskQueue, resolved.workflowName, input.workflowId);
        const status = await handle.status();
        if (status !== 0) {
            return {
                status: 202,
                data: { workflowId: input.workflowId, status: 'running' },
            };
        }
        const result = await handle.result();
        return {
            status: 200,
            data: { workflowId: input.workflowId, result },
        };
    }
    catch (err) {
        if (isResolveError(err))
            return { status: 404, error: err.message };
        return { status: 500, error: err.message };
    }
}
/**
 * Terminate a running workflow.
 *
 * Interrupts the workflow execution immediately via HotMesh.
 *
 * @param input.workflowId — HotMesh workflow ID
 * @returns `{ status: 200, data: { terminated: true, workflowId } }` or 404
 */
async function terminateWorkflow(input) {
    try {
        const resolved = await (0, task_1.resolveWorkflowHandle)(input.workflowId);
        const client = (0, workers_1.createClient)();
        const handle = await client.workflow.getHandle(resolved.taskQueue, resolved.workflowName, input.workflowId);
        await handle.terminate();
        return {
            status: 200,
            data: { terminated: true, workflowId: input.workflowId },
        };
    }
    catch (err) {
        if (isResolveError(err))
            return { status: 404, error: err.message };
        return { status: 500, error: err.message };
    }
}
/**
 * Export the full state of a workflow.
 *
 * Returns the serialized workflow state including all activity
 * results, signals, and metadata.
 *
 * @param input.workflowId — HotMesh workflow ID
 * @returns `{ status: 200, data: <exported state> }` or 404
 */
async function exportWorkflow(input) {
    try {
        const resolved = await (0, task_1.resolveWorkflowHandle)(input.workflowId);
        const exported = await exportService.exportWorkflow(input.workflowId, resolved.taskQueue, resolved.workflowName);
        return { status: 200, data: exported };
    }
    catch (err) {
        if (isResolveError(err))
            return { status: 404, error: err.message };
        return { status: 500, error: err.message };
    }
}
