"use strict";
/*
 * Copyright © 2020 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.GitHubTagRouter = void 0;
const ActionResult_1 = require("@atomist/automation-client/lib/action/ActionResult");
const configuration_1 = require("@atomist/automation-client/lib/configuration");
const GitHubRepoRef_1 = require("@atomist/automation-client/lib/operations/common/GitHubRepoRef");
const httpClient_1 = require("@atomist/automation-client/lib/spi/http/httpClient");
const logger_1 = require("@atomist/automation-client/lib/util/logger");
const _ = require("lodash");
const toToken_1 = require("../../../api-helper/misc/credentials/toToken");
const ghub_1 = require("./ghub");
/**
 * Persist tags to GitHub topics
 * @param {Tags} tags
 * @param params params to this command
 * @return {Promise<ActionResult<Tags>>}
 * @constructor
 */
exports.GitHubTagRouter = async (tags, params) => {
    const grr = GitHubRepoRef_1.isGitHubRepoRef(tags.repoId) ? tags.repoId : new GitHubRepoRef_1.GitHubRepoRef(tags.repoId.owner, tags.repoId.repo, tags.repoId.sha);
    const url = `${grr.scheme}${grr.apiBase}/repos/${grr.owner}/${grr.repo}/topics`;
    const names = _.uniq(tags.tags);
    const httpClient = configuration_1.configurationValue("http.client.factory", httpClient_1.defaultHttpClientFactory()).create();
    logger_1.logger.debug(`Request to '${url}' to raise tags: [${names.join()}]`);
    try {
        await httpClient.exchange(url, {
            body: { names },
            headers: Object.assign(Object.assign({}, ghub_1.authHeaders(toToken_1.toToken(params.targets.credentials)).headers), { Accept: "application/vnd.github.mercy-preview+json" }),
            method: httpClient_1.HttpMethod.Put,
        });
    }
    catch (e) {
        e.message = `Failed to create GitHub topics '${names.join()}' on '${url}': ${e.message}`;
        logger_1.logger.error(e.message);
        throw e;
    }
    return ActionResult_1.successOn(tags);
};
//# sourceMappingURL=gitHubTagRouter.js.map