"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require("tslib");
const QueryString = tslib_1.__importStar(require("querystring"));
const lodash_1 = tslib_1.__importDefault(require("lodash"));
const node_fetch_1 = tslib_1.__importDefault(require("node-fetch"));
const v = tslib_1.__importStar(require("villa"));
const LIST_PULL_MERGE_REQUESTS_CACHE_TIMEOUT = 60 * 1000;
let listPullMergeRequestsCacheTimestamp = 0;
let listPullMergeRequestsCachePromise;
async function listPullMergeRequests(infos) {
    let now = Date.now();
    let promise = listPullMergeRequestsCachePromise;
    // Just ignores infos and returns the cache if not timed out.
    if (!listPullMergeRequestsCachePromise ||
        listPullMergeRequestsCacheTimestamp +
            LIST_PULL_MERGE_REQUESTS_CACHE_TIMEOUT <
            now) {
        listPullMergeRequestsCacheTimestamp = now;
        listPullMergeRequestsCachePromise = v
            .map(infos, async ({ host, project, service: serviceConfig, }) => {
            switch (serviceConfig.type) {
                case 'github':
                    return listGitHubPullRequests(host, project, serviceConfig);
                case 'gitlab':
                    return listGitLabMergeRequests(host, project, serviceConfig);
            }
        })
            .then(lodash_1.default.flatten);
    }
    return promise || listPullMergeRequestsCachePromise;
}
exports.listPullMergeRequests = listPullMergeRequests;
async function listGitHubPullRequests(host, project, { credentials }) {
    let url = `https://api.github.com/repos/${project}/pulls?state=all`;
    let response = await node_fetch_1.default(url, {
        headers: credentials
            ? {
                Authorization: `token ${credentials.accessToken}`,
            }
            : undefined,
    });
    let result = await response.json();
    if (!Array.isArray(result)) {
        console.error(`Result requesting GitHub project "${project}" pull requests is not an array:`);
        console.error(result);
        return [];
    }
    return result.map((entry) => {
        return {
            url: entry.html_url,
            host,
            project,
            id: entry.number,
            state: entry.state === 'open'
                ? 'opened'
                : entry.merged_at
                    ? 'merged'
                    : 'closed',
            sourceBranch: entry.head.ref,
            targetBranch: entry.base.ref,
        };
    });
    return [];
}
async function listGitLabMergeRequests(host, project, { url: baseURL = `https://${host}`, credentials }) {
    let url = `${baseURL}/api/v4/projects/${encodeURIComponent(project)}/merge_requests?state=all`;
    let response = await node_fetch_1.default(url, {
        headers: credentials
            ? {
                'Private-Token': credentials.accessToken,
            }
            : undefined,
    });
    let result = await response.json();
    if (!Array.isArray(result)) {
        console.error(`Result requesting GitLab "${baseURL}" project "${project}" merge requests is not an array:`);
        console.error(result);
        return [];
    }
    return result.map((entry) => {
        return {
            url: entry.web_url,
            host,
            project,
            id: entry.iid,
            state: entry.state,
            sourceBranch: entry.source_branch,
            targetBranch: entry.target_branch,
        };
    });
}
function generateCreatePullMergeRequestInfo(host, project, sourceBranch, targetBranch, serviceConfig) {
    switch (serviceConfig.type) {
        case 'github':
            return {
                text: 'pull request',
                url: `https://github.com/${project}/compare/${targetBranch}...${sourceBranch}?expand=1`,
            };
        case 'gitlab': {
            let { url: baseURL = `https://${host}` } = serviceConfig;
            return {
                text: 'merge request',
                url: `${baseURL}/${project}/merge_requests/new?${QueryString.stringify({
                    'merge_request[source_branch]': sourceBranch,
                    'merge_request[target_branch]': targetBranch,
                })}`,
            };
        }
    }
}
exports.generateCreatePullMergeRequestInfo = generateCreatePullMergeRequestInfo;
//# sourceMappingURL=@git-services.js.map