import { AsyncJobManager } from "./job-manager.js";
export function createSessionAsyncDeliveryHandler(session, manager, sessionId) {
    return async (message) => {
        const isStale = () => manager?.disposed === true ||
            manager?.isDeliverySuppressed(message.details.jobId) === true ||
            (sessionId !== undefined && manager?.isSessionDisposed(sessionId) === true);
        if (isStale())
            return;
        await session.sendCustomMessage(message, {
            deliverAs: "followUp",
            triggerTurn: true,
            stageAdmissionKey: `async-job:${message.details.jobId}`,
        });
    };
}
export function createSessionAsyncJobManager(session) {
    const existing = AsyncJobManager.instance();
    if (existing)
        return { manager: existing, owns: false, sessionId: existing.registerSession() };
    let manager;
    manager = new AsyncJobManager({
        onJobComplete: (message) => createSessionAsyncDeliveryHandler(session, manager)(message),
    });
    AsyncJobManager.setInstance(manager);
    return { manager, owns: true, sessionId: manager.registerSession() };
}
export function disposeSessionAsyncJobManager(manager, sessionId) {
    if (!manager || !sessionId)
        return;
    manager.releaseSession(sessionId);
    if (manager.disposed && AsyncJobManager.instance() === manager)
        AsyncJobManager.setInstance(undefined);
}
//# sourceMappingURL=session-manager.js.map