"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createExecutionOwnership = createExecutionOwnership;
exports.refreshExecutionOwnership = refreshExecutionOwnership;
exports.isExecutionOwnershipActive = isExecutionOwnershipActive;
exports.isExecutionOwnershipOwnedBy = isExecutionOwnershipOwnedBy;
exports.stripExecutionOwnership = stripExecutionOwnership;
exports.withExecutionOwnership = withExecutionOwnership;
const node_crypto_1 = require("node:crypto");
function createExecutionOwnership(input) {
    const now = input.now ?? new Date();
    return {
        workerId: input.workerIdentity.workerId,
        runId: (0, node_crypto_1.randomUUID)(),
        claimedAt: now.toISOString(),
        heartbeatAt: now.toISOString(),
        expiresAt: new Date(now.getTime() + input.pollIntervalSec * 3 * 1_000).toISOString(),
    };
}
function refreshExecutionOwnership(ownership, pollIntervalSec, now = new Date()) {
    return {
        ...ownership,
        heartbeatAt: now.toISOString(),
        expiresAt: new Date(now.getTime() + pollIntervalSec * 3 * 1_000).toISOString(),
    };
}
function isExecutionOwnershipActive(ownership, now = new Date()) {
    if (!ownership) {
        return false;
    }
    const expiresAt = Date.parse(ownership.expiresAt);
    return !Number.isNaN(expiresAt) && expiresAt > now.getTime();
}
function isExecutionOwnershipOwnedBy(ownership, input) {
    return (ownership?.workerId === input.workerId && ownership?.runId === input.runId);
}
function stripExecutionOwnership(workflowState) {
    if (workflowState.executionOwnership === undefined) {
        return workflowState;
    }
    const { executionOwnership: _ignored, ...rest } = workflowState;
    return rest;
}
function withExecutionOwnership(workflowState, executionOwnership) {
    return {
        ...workflowState,
        executionOwnership,
    };
}
