"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.loadPullRequestIssueForHandoff = loadPullRequestIssueForHandoff;
exports.appendSourcePullRequestHandoffLink = appendSourcePullRequestHandoffLink;
const catalog_1 = require("../../i18n/catalog");
const errors_1 = require("../../platform/ticket-tracker/errors");
const types_1 = require("../../platform/ticket-tracker/types");
const publisher_events_1 = require("../../workflows/publisher-events");
async function loadPullRequestIssueForHandoff(context) {
    try {
        return {
            issue: await context.ticketTracker.getIssue(context.state.pullRequestThreadId),
            allowInitialTitleSync: true,
            currentLabelNames: undefined,
        };
    }
    catch (error) {
        if (!(0, errors_1.isTrackerMissingWorkflowLabelSetError)(error)) {
            throw error;
        }
    }
    const issueRecord = await context.ticketTracker.getIssueRecord(context.state.pullRequestThreadId);
    return {
        issue: buildPullRequestIssueForHandoff({
            issueRecord,
            sourceBranchName: context.state.branchName,
            workflowState: context.state.handoffPullRequestSnapshot,
        }),
        allowInitialTitleSync: false,
        currentLabelNames: issueRecord.labelNames ?? [],
    };
}
function appendSourcePullRequestHandoffLink(input) {
    if (input.visibleUpdate === null ||
        input.visibleUpdate.kind !== "workflow_update" ||
        input.visibleUpdate.event !== publisher_events_1.WORKFLOW_VISIBLE_EVENTS.prHandoff ||
        input.visibleUpdate.summary.includes(input.pullRequestIssue.url)) {
        return input.visibleUpdate;
    }
    const pullRequestLink = `[${input.pullRequestIssue.displayId}](${input.pullRequestIssue.url})`;
    const pullRequestSection = [
        (0, catalog_1.translate)(input.responseLanguage, "run.presentation.prHandoff.sourcePullRequestSummary"),
        [
            `## ${(0, catalog_1.translate)(input.responseLanguage, "run.presentation.prHandoff.sourcePullRequestHeading")}`,
            "",
            `- ${(0, catalog_1.translate)(input.responseLanguage, "run.presentation.prHandoff.sourcePullRequestLink", { pullRequestLink })}`,
            `- ${(0, catalog_1.translate)(input.responseLanguage, "run.presentation.prHandoff.sourcePullRequestNext")}`,
        ].join("\n"),
    ].join("\n\n");
    return {
        ...input.visibleUpdate,
        summary: [input.visibleUpdate.summary, pullRequestSection].join("\n\n"),
    };
}
function buildPullRequestIssueForHandoff(input) {
    if (input.issueRecord.kind !== types_1.TRACKER_ITEM_KINDS.pullRequest) {
        throw new Error("Expected PR handoff target to be a pull request.");
    }
    return {
        ...input.issueRecord,
        sourceBranchName: input.issueRecord.sourceBranchName ?? input.sourceBranchName,
        workflowState: { ...input.workflowState },
        labelNames: input.issueRecord.labelNames ?? [],
    };
}
