"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.buildCodeCommitClient = buildCodeCommitClient;
exports.deleteComment = deleteComment;
exports.getPrComments = getPrComments;
exports.updateComment = updateComment;
exports.createPrComment = createPrComment;
exports.updatePrStatus = updatePrStatus;
exports.updatePrTitle = updatePrTitle;
exports.updatePrDescription = updatePrDescription;
exports.createPr = createPr;
exports.getFile = getFile;
exports.listPullRequests = listPullRequests;
exports.getRepositoryInfo = getRepositoryInfo;
exports.getPr = getPr;
exports.listRepositories = listRepositories;
exports.createPrApprovalRule = createPrApprovalRule;
exports.getCodeCommitUrl = getCodeCommitUrl;
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() {
    if (!codeCommitClient) {
        codeCommitClient = new client_codecommit_1.CodeCommitClient({});
    }
    // istanbul ignore if
    if (!codeCommitClient) {
        throw new Error('Failed to initialize codecommit client');
    }
}
async function deleteComment(commentId) {
    const input = {
        commentId,
    };
    const cmd = new client_codecommit_1.DeleteCommentContentCommand(input);
    return await codeCommitClient.send(cmd);
}
async function getPrComments(pullRequestId) {
    const input = {
        pullRequestId,
    };
    const cmd = new client_codecommit_1.GetCommentsForPullRequestCommand(input);
    return await codeCommitClient.send(cmd);
}
async function updateComment(commentId, content) {
    const input = {
        commentId,
        content,
    };
    const cmd = new client_codecommit_1.UpdateCommentCommand(input);
    return await codeCommitClient.send(cmd);
}
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);
}
// 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);
}
async function updatePrTitle(prNo, title) {
    const input = {
        pullRequestId: `${prNo}`,
        title,
    };
    const cmd = new client_codecommit_1.UpdatePullRequestTitleCommand(input);
    return await codeCommitClient.send(cmd);
}
async function updatePrDescription(pullRequestId, description) {
    const input = {
        pullRequestId,
        description,
    };
    const cmd = new client_codecommit_1.UpdatePullRequestDescriptionCommand(input);
    return await codeCommitClient.send(cmd);
}
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);
}
async function getFile(repositoryName, filePath, commitSpecifier) {
    const input = {
        repositoryName,
        filePath,
        commitSpecifier,
    };
    const cmd = new client_codecommit_1.GetFileCommand(input);
    return await codeCommitClient.send(cmd);
}
async function listPullRequests(repositoryName) {
    const input = {
        repositoryName,
        pullRequestStatus: client_codecommit_1.PullRequestStatusEnum.OPEN,
    };
    const cmd = new client_codecommit_1.ListPullRequestsCommand(input);
    return await codeCommitClient.send(cmd);
}
async function getRepositoryInfo(repository) {
    const input = {
        repositoryName: `${repository}`,
    };
    const cmd = new client_codecommit_1.GetRepositoryCommand(input);
    return await codeCommitClient.send(cmd);
}
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;
}
async function listRepositories() {
    const input = {};
    const cmd = new client_codecommit_1.ListRepositoriesCommand(input);
    return await codeCommitClient.send(cmd);
}
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);
}
function getCodeCommitUrl(repoMetadata, repoName) {
    logger_1.logger.debug('get code commit url');
    if (!process.env.AWS_ACCESS_KEY_ID || !process.env.AWS_SECRET_ACCESS_KEY) {
        if (repoMetadata.cloneUrlHttp) {
            return repoMetadata.cloneUrlHttp;
        }
        // shouldn't reach here, but just in case
        return `https://git-codecommit.${process.env.AWS_REGION ?? 'us-east-1'}.amazonaws.com/v1/repos/${repoName}`;
    }
    const signer = new aws4.RequestSigner({
        service: 'codecommit',
        host: `git-codecommit.${process.env.AWS_REGION ?? 'us-east-1'}.amazonaws.com`,
        method: 'GIT',
        path: `v1/repos/${repoName}`,
    });
    const dateTime = signer.getDateTime();
    /* istanbul ignore if */
    if (!is_1.default.string(dateTime)) {
        throw new Error(error_messages_1.REPOSITORY_UNINITIATED);
    }
    const token = `${dateTime}Z${signer.signature()}`;
    let username = `${process.env.AWS_ACCESS_KEY_ID}${process.env.AWS_SESSION_TOKEN ? `%${process.env.AWS_SESSION_TOKEN}` : ''}`;
    // massaging username with the session token,
    // istanbul ignore if
    if (username.includes('/')) {
        username = username.replace(/\//g, '%2F');
    }
    return `https://${username}:${token}@git-codecommit.${process.env.AWS_REGION ?? 'us-east-1'}.amazonaws.com/v1/repos/${repoName}`;
}
//# sourceMappingURL=codecommit-client.js.map