"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.publishServiceRuntimeConfigScanPlan = publishServiceRuntimeConfigScanPlan;
const runner_1 = require("../../event-hooks/runner");
const publisher_1 = require("../../workflows/publisher");
async function publishServiceRuntimeConfigScanPlan(input) {
    if (input.plan === undefined || input.plan === null) {
        return null;
    }
    if (input.plan.kind === "noop") {
        return null;
    }
    const publisher = (0, publisher_1.createWorkflowPublisher)({
        repoRoot: input.repoRoot,
        ticketTrackerKind: input.ticketTrackerKind,
        displayTimeZone: input.displayTimeZone,
        workflowLabels: input.workflowLabels,
        ticketTracker: input.ticketTracker,
    });
    const result = await publisher.publishWorkflow(input.plan.publish.request);
    if (input.eventHooks !== undefined) {
        await (0, runner_1.runEventHooksForPublications)({
            repoRoot: input.repoRoot,
            config: input.eventHooks.config,
            publications: [
                {
                    request: input.plan.publish.request,
                    result,
                    origin: input.eventHooks.origin ?? "worker_publish",
                    run: input.eventHooks.run ?? null,
                },
            ],
            ...(input.eventHooks.worker !== undefined
                ? { worker: input.eventHooks.worker }
                : {}),
            ...(input.eventHooks.homeDirectory !== undefined
                ? { homeDirectory: input.eventHooks.homeDirectory }
                : {}),
        });
    }
    applyServiceRuntimeConfigPublishResultToOpenIssues({
        openIssues: input.openIssues,
        result,
    });
    return result;
}
function applyServiceRuntimeConfigPublishResultToOpenIssues(input) {
    const openIssues = input.openIssues;
    if (openIssues === undefined) {
        return;
    }
    const issue = openIssues.find((entry) => entry.id === input.result.targetIssue.id);
    if (issue === undefined) {
        return;
    }
    Object.assign(issue, buildRefreshedOpenIssue(issue, input.result));
}
function buildRefreshedOpenIssue(existingIssue, result) {
    return {
        ...existingIssue,
        ...result.targetIssue,
        workflowState: result.targetWorkflowProjection !== null
            ? {
                status: result.targetWorkflowProjection.status,
                rules: [...result.targetWorkflowProjection.rules],
            }
            : existingIssue.workflowState,
        ...(result.targetClosed ? { isOpen: false } : {}),
    };
}
