"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.compareTrackerComments = compareTrackerComments;
exports.buildTrackerCommentTarget = buildTrackerCommentTarget;
exports.buildTrackerCommentTargetFromCommentUrl = buildTrackerCommentTargetFromCommentUrl;
exports.resolveTrackerIssueNumberFromApiUrl = resolveTrackerIssueNumberFromApiUrl;
const types_1 = require("./types");
const TRACKER_COMMENT_KIND_ORDER = {
    [types_1.TRACKER_COMMENT_KINDS.issueComment]: 0,
    [types_1.TRACKER_COMMENT_KINDS.pullRequestReview]: 1,
    [types_1.TRACKER_COMMENT_KINDS.pullRequestReviewComment]: 2,
};
function compareTrackerComments(left, right) {
    const createdAtComparison = left.createdAt.localeCompare(right.createdAt);
    if (createdAtComparison !== 0) {
        return createdAtComparison;
    }
    const kindComparison = TRACKER_COMMENT_KIND_ORDER[left.kind] -
        TRACKER_COMMENT_KIND_ORDER[right.kind];
    if (kindComparison !== 0) {
        return kindComparison;
    }
    return left.id.localeCompare(right.id);
}
function buildTrackerCommentTarget(input) {
    const targetDisplayId = input.issueNumber === null ? "#?" : `#${input.issueNumber}`;
    if (input.isPullRequest) {
        return {
            targetKind: types_1.TRACKER_ITEM_KINDS.pullRequest,
            targetDisplayId,
            targetUrl: input.issueUrl,
            pullRequestUrl: input.issueUrl,
            ...(input.issueNumber === null
                ? {}
                : { pullRequestNumber: input.issueNumber }),
        };
    }
    return {
        targetKind: types_1.TRACKER_ITEM_KINDS.issue,
        targetDisplayId,
        targetUrl: input.issueUrl,
    };
}
function buildTrackerCommentTargetFromCommentUrl(input) {
    const targetUrl = input.commentUrl.replace(/#.*$/, "");
    if (input.isPullRequest === true ||
        /\/pulls?\/\d+(?:[?#/]|$)/.test(targetUrl)) {
        return {
            targetKind: types_1.TRACKER_ITEM_KINDS.pullRequest,
            targetDisplayId: `#${input.issueNumber}`,
            targetUrl,
            pullRequestNumber: input.issueNumber,
            pullRequestUrl: targetUrl,
        };
    }
    return {
        targetKind: types_1.TRACKER_ITEM_KINDS.issue,
        targetDisplayId: `#${input.issueNumber}`,
        targetUrl,
    };
}
function resolveTrackerIssueNumberFromApiUrl(issueUrl) {
    if (!issueUrl) {
        return null;
    }
    const match = issueUrl.match(/\/(?:issues|pulls?)\/(\d+)(?:[?#/]|$)/);
    return match?.[1] ? Number(match[1]) : null;
}
