"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.PULL_REQUEST_COMPLETION_REASONS = void 0;
exports.resolvePullRequestCompletion = resolvePullRequestCompletion;
exports.isPullRequestHeadIncludedInBase = isPullRequestHeadIncludedInBase;
const constants_1 = require("../../platform/constants");
const log_text_1 = require("../log-text");
const effect_log_1 = require("./effect-log");
exports.PULL_REQUEST_COMPLETION_REASONS = {
    merged: "merged",
    headIncluded: "head_included",
};
async function resolvePullRequestCompletion(input) {
    if (input.pullRequest === null) {
        return { status: "not_completed" };
    }
    if (input.pullRequest.state === constants_1.PLATFORM_PULL_REQUEST_STATES.merged) {
        return {
            status: "completed",
            reason: exports.PULL_REQUEST_COMPLETION_REASONS.merged,
            pullRequest: input.pullRequest,
        };
    }
    if (input.pullRequest.state !== constants_1.PLATFORM_PULL_REQUEST_STATES.open) {
        return { status: "not_completed" };
    }
    const headIncluded = await isPullRequestHeadIncludedInBase({
        repositoryHost: input.repositoryHost,
        pullRequestNumber: input.pullRequest.number,
    });
    if (!headIncluded) {
        return { status: "not_completed" };
    }
    if (input.logger !== undefined) {
        await (0, effect_log_1.appendEffectResultLog)(input.logger, [
            (0, log_text_1.issueLogField)("effect", "detect_pull_request_completion"),
            (0, log_text_1.issueLogField)("pr", input.pullRequest.url),
            (0, log_text_1.issueLogField)("branch", input.branchName ?? input.pullRequest.headBranch),
            (0, log_text_1.issueLogField)("note", "branch_already_in_target"),
        ]);
    }
    return {
        status: "completed",
        reason: exports.PULL_REQUEST_COMPLETION_REASONS.headIncluded,
        pullRequest: input.pullRequest,
    };
}
async function isPullRequestHeadIncludedInBase(input) {
    try {
        return await input.repositoryHost.isPullRequestHeadIncludedInBase(input.pullRequestNumber);
    }
    catch {
        return false;
    }
}
