"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.loadPostCompletionCommentCandidates = loadPostCompletionCommentCandidates;
const shared_1 = require("../run/run-once-cycle/shared");
const workflow_timeline_scan_1 = require("../workflows/workflow-timeline-scan");
async function loadPostCompletionCommentCandidates(input) {
    const issueComments = [...input.issueComments];
    if (input.pr === null) {
        return { issueComments, prComments: [] };
    }
    const prThread = await tryLoadPullRequestThreadRecord({
        ticketTracker: input.ticketTracker,
        pr: input.pr,
    });
    if (prThread === null || prThread.id === input.issue.id) {
        return { issueComments, prComments: [] };
    }
    const prComments = await (0, shared_1.loadSortedIssueComments)(input.ticketTracker, prThread.id);
    return {
        issueComments,
        prComments: mergeTimelineComments(prComments),
    };
}
async function tryLoadPullRequestThreadRecord(input) {
    try {
        return await input.ticketTracker.getPullRequestThreadRecord({
            pullRequestNumber: input.pr.number,
            pullRequestUrl: input.pr.url,
        });
    }
    catch {
        return null;
    }
}
function mergeTimelineComments(comments) {
    const byKey = new Map();
    for (const comment of comments) {
        byKey.set(`${comment.targetKind}:${comment.targetDisplayId}:${comment.id}`, comment);
    }
    return (0, workflow_timeline_scan_1.sortTimelineComments)([...byKey.values()]);
}
