"use strict";
/*
 * Copyright © 2019 Atomist, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.githubTeamVoter = exports.gitHubTeamVoter = void 0;
const secured_1 = require("@atomist/automation-client/lib/secured");
const httpClient_1 = require("@atomist/automation-client/lib/spi/http/httpClient");
const _ = require("lodash");
const goalApprovalRequestVote_1 = require("../../api/registration/goalApprovalRequestVote");
/**
 * Goal approval request vote implementation that checks for GitHub team membership of the
 * person who is requesting the approval .
 * @param {string} team
 */
function gitHubTeamVoter(team = "atomist-automation") {
    return async (gai) => {
        const approval = gai.goal.approval ? gai.goal.approval : gai.goal.preApproval;
        const repo = gai.goal.repo;
        const result = await gai.context.graphClient.query({
            name: "GitHubLogin",
            variables: {
                userId: approval.userId,
                owner: repo.owner,
                providerId: repo.providerId,
            },
        });
        const apiUrl = _.get(result, "Team[0].orgs[0].provider.apiUrl");
        let login = _.get(result, "Team[0].chatTeams[0].members[0].person.gitHubId.login");
        if (!login) {
            const httpClient = gai.configuration.http.client.factory.create(apiUrl);
            const user = await httpClient.exchange(`${apiUrl}user`, {
                method: httpClient_1.HttpMethod.Get,
                headers: {
                    Authorization: `token ${gai.credentials.token}`,
                },
            });
            login = user.body.login;
        }
        login = login || approval.userId;
        if (await secured_1.isGitHubTeamMember(repo.owner, login, team, gai.credentials.token, apiUrl)) {
            return {
                vote: goalApprovalRequestVote_1.GoalApprovalRequestVote.Granted,
            };
        }
        else {
            return {
                vote: goalApprovalRequestVote_1.GoalApprovalRequestVote.Denied,
                reason: `User ${login} not in GitHub team ${team}`,
            };
        }
    };
}
exports.gitHubTeamVoter = gitHubTeamVoter;
/**
 * @Deprecated since 1.0.0 use gitHubTeamVoter instead
 */
exports.githubTeamVoter = gitHubTeamVoter;
//# sourceMappingURL=githubTeamVoter.js.map