"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.postChangelogToSlack = void 0;
const web_api_1 = require("@slack/web-api");
const outdent_1 = require("outdent");
const conventionalChangelog = require("conventional-changelog");
const SLACK_TIMEOUT_MS = 30000;
const formatCommitsToSlackMarkdown = (changelog) => {
    return changelog.commitGroups
        .map(group => {
        return outdent_1.outdent `
            *${group.title}*
            ${group.commits
            .map(commit => `- ${commit.subject} <${changelog.repoUrl}/commit/${commit.hash}|${commit.shortHash}>`)
            .join("\n")}

        `;
    })
        .join("\n");
};
exports.postChangelogToSlack = async (token, channelId, oldVersion, newVersion, env, user, ciRun) => {
    if (oldVersion === newVersion) {
        console.log(`Deployed versions did not change, refusing to post to slack.`);
        return;
    }
    console.log(`Generating changelog for version: ${oldVersion} -> ${newVersion} in env ${env} for ${user}@ci:${ciRun}`);
    const web = new web_api_1.WebClient(token);
    const changelogs = await Promise.race([
        new Promise((resolve, reject) => {
            let nextTimer;
            const rawCommits = [];
            conventionalChangelog({
                preset: "angular",
                debug: (output) => {
                    if (output.includes("Your final context is")) {
                        try {
                            const commits = JSON.parse(output.replace("Your final context is:\n", ""));
                            rawCommits.push(commits);
                            if (nextTimer) {
                                clearTimeout(nextTimer);
                            }
                            nextTimer = setTimeout(() => resolve(rawCommits), 200);
                        }
                        catch (e) {
                            reject(e);
                        }
                    }
                },
            }, {
                previousTag: oldVersion,
                currentTag: newVersion.replace("v", ""),
            }, {
                from: oldVersion,
            });
        }),
        new Promise((_, reject) => {
            const timer = setTimeout(() => reject(new Error("Timeout while trying to generate changelog")), SLACK_TIMEOUT_MS);
            timer.unref();
        }),
    ]);
    if (!changelogs.length) {
        console.log(`Did not generate any changelog w/ standard-version, refusing to send`);
        return;
    }
    let filteredChangelogs = [];
    for (const changelog of changelogs.reverse()) {
        if (changelog.version === newVersion.replace("v", "")) {
            filteredChangelogs.push(changelog);
            break;
        }
        filteredChangelogs.push(changelog);
    }
    filteredChangelogs = filteredChangelogs.reverse();
    const commitGroups = Object.values(changelogs.reduce((acc, changelog) => {
        if (!changelog.commitGroups.length) {
            return acc;
        }
        return changelog.commitGroups.reduce((innerAcc, commitGroup) => {
            if (!innerAcc[commitGroup.title]) {
                acc[commitGroup.title] = { title: commitGroup.title, commits: [] };
            }
            acc[commitGroup.title].commits.push(...commitGroup.commits);
            return acc;
        }, acc);
    }, {}));
    const changelog = Object.assign(Object.assign({}, changelogs[0]), { commitGroups });
    const changelogGithubUrl = `https://github.com/figedi/${changelog.repository}/compare/${oldVersion}...${newVersion}`;
    await web.chat.postMessage({
        channel: channelId,
        text: "",
        attachments: [
            {
                author_icon: "https://www.guardicore.com/wp-content/uploads/2019/03/kubernetes-logo-4.png",
                thumb_url: "https://www.guardicore.com/wp-content/uploads/2019/03/kubernetes-logo-4.png",
                color: "#36a64f",
                fallback: `A new deployment to env ${env} was triggered by ${user}`,
                pretext: `A new deployment to env *${env}* was triggered by *${user}*`,
                fields: [
                    {
                        title: "Service",
                        value: changelog.repository,
                        short: true,
                    },
                    {
                        title: "Environment",
                        value: env,
                        short: true,
                    },
                    {
                        title: "Version",
                        value: `${oldVersion} → ${newVersion}`,
                        short: false,
                    },
                ],
                actions: [
                    {
                        type: "button",
                        text: "Github repo",
                        url: changelog.repoUrl,
                    },
                    {
                        type: "button",
                        text: `Github diff`,
                        url: changelogGithubUrl,
                    },
                    {
                        type: "button",
                        text: `CI-run`,
                        url: `https://circleci.com/gh/figedi/${changelog.repository}/${ciRun}`,
                    },
                ],
            },
            changelog.commitGroups.length
                ? {
                    fallback: `View changelog: ${changelogGithubUrl}`,
                    pretext: `Changelog from *${oldVersion}* to *${newVersion}*`,
                    text: formatCommitsToSlackMarkdown(changelog),
                    mrkdwn_in: ["text", "pretext"],
                    ts: (Date.now() / 1000),
                }
                : {
                    text: ":bomb: Could not generate changelog, here is a git-version",
                    actions: [
                        {
                            type: "button",
                            text: `Changelog ${oldVersion} → ${newVersion}`,
                            url: changelogGithubUrl,
                        },
                    ],
                },
        ],
    });
};
//# sourceMappingURL=postChangelogToSlack.js.map