"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getCodeCommitUrl = exports.createPrApprovalRule = exports.listRepositories = exports.getPr = exports.getRepositoryInfo = exports.listPullRequests = exports.getFile = exports.createPr = exports.updatePrDescription = exports.updatePrTitle = exports.updatePrStatus = exports.getPrEvents = exports.createPrComment = exports.updateComment = exports.getPrComments = exports.deleteComment = exports.buildCodeCommitClient = void 0;
const tslib_1 = require("tslib");
const client_codecommit_1 = require("@aws-sdk/client-codecommit");
const is_1 = tslib_1.__importDefault(require("@sindresorhus/is"));
const aws4 = tslib_1.__importStar(require("aws4"));
const error_messages_1 = require("../../../constants/error-messages");
const logger_1 = require("../../../logger");
let codeCommitClient;
function buildCodeCommitClient(region, credentials) {
    if (!codeCommitClient) {
        codeCommitClient = new client_codecommit_1.CodeCommitClient({
            region,
            credentials,
        });
    }
    // istanbul ignore if
    if (!codeCommitClient) {
        throw new Error('Failed to initialize codecommit client');
    }
}
exports.buildCodeCommitClient = buildCodeCommitClient;
async function deleteComment(commentId) {
    const input = {
        commentId,
    };
    const cmd = new client_codecommit_1.DeleteCommentContentCommand(input);
    return await codeCommitClient.send(cmd);
}
exports.deleteComment = deleteComment;
async function getPrComments(repositoryName, pullRequestId) {
    const input = {
        repositoryName,
        pullRequestId,
    };
    const cmd = new client_codecommit_1.GetCommentsForPullRequestCommand(input);
    return await codeCommitClient.send(cmd);
}
exports.getPrComments = getPrComments;
async function updateComment(commentId, content) {
    const input = {
        commentId,
        content,
    };
    const cmd = new client_codecommit_1.UpdateCommentCommand(input);
    return await codeCommitClient.send(cmd);
}
exports.updateComment = updateComment;
async function createPrComment(pullRequestId, repositoryName, content, beforeCommitId, afterCommitId) {
    const input = {
        pullRequestId,
        repositoryName,
        content,
        afterCommitId,
        beforeCommitId,
    };
    const cmd = new client_codecommit_1.PostCommentForPullRequestCommand(input);
    return await codeCommitClient.send(cmd);
}
exports.createPrComment = createPrComment;
async function getPrEvents(pullRequestId) {
    const input = {
        pullRequestId,
        pullRequestEventType: client_codecommit_1.PullRequestEventType.PULL_REQUEST_SOURCE_REFERENCE_UPDATED,
    };
    const cmd = new client_codecommit_1.DescribePullRequestEventsCommand(input);
    return await codeCommitClient.send(cmd);
}
exports.getPrEvents = getPrEvents;
// export async function fastForwardMerge(
//   repositoryName: string,
//   sourceCommitSpecifier: string,
//   destinationReference: string
// ): Promise<MergeBranchesByFastForwardOutput> {
//   const input: MergeBranchesByFastForwardInput = {
//     repositoryName,
//     sourceCommitSpecifier,
//     destinationCommitSpecifier: destinationReference,
//     targetBranch: destinationReference,
//   };
//   const cmd = new MergeBranchesByFastForwardCommand(input);
//   return await codeCommitClient.send(cmd);
// }
// export async function squashMerge(
//   repositoryName: string,
//   sourceCommitSpecifier: string,
//   destinationReference: string,
//   commitMessage: string | undefined
// ): Promise<MergeBranchesBySquashOutput> {
//   const input: MergeBranchesBySquashInput = {
//     repositoryName,
//     sourceCommitSpecifier,
//     destinationCommitSpecifier: destinationReference,
//     targetBranch: destinationReference,
//     commitMessage,
//   };
//   const cmd = new MergeBranchesBySquashCommand(input);
//   return await codeCommitClient.send(cmd);
// }
async function updatePrStatus(pullRequestId, pullRequestStatus) {
    const input = {
        pullRequestId,
        pullRequestStatus,
    };
    const cmd = new client_codecommit_1.UpdatePullRequestStatusCommand(input);
    return await codeCommitClient.send(cmd);
}
exports.updatePrStatus = updatePrStatus;
async function updatePrTitle(prNo, title) {
    const input = {
        pullRequestId: `${prNo}`,
        title,
    };
    const cmd = new client_codecommit_1.UpdatePullRequestTitleCommand(input);
    return await codeCommitClient.send(cmd);
}
exports.updatePrTitle = updatePrTitle;
async function updatePrDescription(pullRequestId, description) {
    const input = {
        pullRequestId,
        description,
    };
    const cmd = new client_codecommit_1.UpdatePullRequestDescriptionCommand(input);
    return await codeCommitClient.send(cmd);
}
exports.updatePrDescription = updatePrDescription;
async function createPr(title, description, sourceReference, destinationReference, repositoryName) {
    const input = {
        title,
        description,
        targets: [
            {
                sourceReference,
                destinationReference,
                repositoryName,
            },
        ],
    };
    const cmd = new client_codecommit_1.CreatePullRequestCommand(input);
    return await codeCommitClient.send(cmd);
}
exports.createPr = createPr;
async function getFile(repositoryName, filePath, commitSpecifier) {
    const input = {
        repositoryName,
        filePath,
        commitSpecifier,
    };
    const cmd = new client_codecommit_1.GetFileCommand(input);
    return await codeCommitClient.send(cmd);
}
exports.getFile = getFile;
async function listPullRequests(repositoryName, authorArn) {
    const input = {
        repositoryName,
        authorArn,
        pullRequestStatus: client_codecommit_1.PullRequestStatusEnum.OPEN,
    };
    const cmd = new client_codecommit_1.ListPullRequestsCommand(input);
    return await codeCommitClient.send(cmd);
}
exports.listPullRequests = listPullRequests;
async function getRepositoryInfo(repository) {
    const input = {
        repositoryName: `${repository}`,
    };
    const cmd = new client_codecommit_1.GetRepositoryCommand(input);
    return await codeCommitClient.send(cmd);
}
exports.getRepositoryInfo = getRepositoryInfo;
async function getPr(pullRequestId) {
    const input = {
        pullRequestId,
    };
    const cmd = new client_codecommit_1.GetPullRequestCommand(input);
    let res;
    try {
        res = await codeCommitClient.send(cmd);
    }
    catch (err) {
        logger_1.logger.debug({ err }, 'failed to get PR using prId');
    }
    return res;
}
exports.getPr = getPr;
async function listRepositories() {
    const input = {};
    const cmd = new client_codecommit_1.ListRepositoriesCommand(input);
    return await codeCommitClient.send(cmd);
}
exports.listRepositories = listRepositories;
async function createPrApprovalRule(pullRequestId, approvalRuleContent) {
    const input = {
        approvalRuleContent,
        approvalRuleName: 'Reviewers By Renovate',
        pullRequestId,
    };
    const cmd = new client_codecommit_1.CreatePullRequestApprovalRuleCommand(input);
    return await codeCommitClient.send(cmd);
}
exports.createPrApprovalRule = createPrApprovalRule;
function getCodeCommitUrl(region, repoName, credentials) {
    const signer = new aws4.RequestSigner({
        service: 'codecommit',
        host: `git-codecommit.${region}.amazonaws.com`,
        method: 'GIT',
        path: `v1/repos/${repoName}`,
    }, credentials);
    const dateTime = signer.getDateTime();
    /* istanbul ignore if */
    if (!is_1.default.string(dateTime)) {
        throw new Error(error_messages_1.REPOSITORY_UNINITIATED);
    }
    const accessKeyId = credentials.accessKeyId;
    const token = `${dateTime}Z${signer.signature()}`;
    let username = `${accessKeyId}${credentials.sessionToken ? `%${credentials.sessionToken}` : ''}`;
    // massaging username with the session token,
    // istanbul ignore if
    if (username.includes('/')) {
        username = username.replace(/\//g, '%2F');
    }
    return `https://${username}:${token}@git-codecommit.${region}.amazonaws.com/v1/repos/${repoName}`;
}
exports.getCodeCommitUrl = getCodeCommitUrl;
//# sourceMappingURL=codecommit-client.js.map