/* eslint-disable no-console */
const fetch = require('node-fetch');
const QloudApi = require('qloud-api');
const stClient = require('st-client');
const RegistryApi = require('./clients/RegistryApi');

const PROJECT_NAME = 'workspace';
const APPLICATION_NAME = 'portal';

const CONNECT_REPOSITORY = 'yandex-directory/connect';

const ApiHosts = {
    GITHUB: 'https://api.github.yandex-team.ru',
    QLOUD: 'https://platform.yandex-team.ru',
};

const {
    CONNECT_QLOUD_OAUTH_TOKEN,
    CONNECT_GITHUB_OAUTH_TOKEN,
    CONNECT_TRACKER_OAUTH_TOKEN,
    TRENDBOX_PULL_REQUEST_NUMBER,
} = process.env;

const qloudApi = new QloudApi({
    token: CONNECT_QLOUD_OAUTH_TOKEN,
    host: ApiHosts.QLOUD,
});

const registryApi = new RegistryApi({
    token: CONNECT_QLOUD_OAUTH_TOKEN,
    repo: 'workspace/portal',
});

const trackerApi = stClient.init({
    token: CONNECT_TRACKER_OAUTH_TOKEN,
});

async function createTrackerComment(ticket, text) {
    try {
        trackerApi.createIssueComment(ticket, { text });
    } catch (e) {
        console.error(`Не удалось добавить комментарий к тикету ${ticket}`, e);
    }
}

async function removeEnv(branchName) {
    const envName = branchName.toLowerCase();
    const envId = `${PROJECT_NAME}.${APPLICATION_NAME}.${envName}`;
    let response;

    try {
        response = await qloudApi.deleteEnvironment(envId);

        console.log(`Запущено удаление окружения ${envName}`);
        await createTrackerComment(branchName, `Запущено удаление окружения ${envId}`);
    } catch (e) {
        console.error(`Не удалось удалить окружение ${envName}`, e);
        await createTrackerComment(branchName, `Не удалось удалить окружение ${envId}`);
    }

    return response;
}

async function removeDockerPackage(version) {
    try {
        await registryApi.remove(version);

        await createTrackerComment(version, `Удален пакет ${version}`);
    } catch (e) {
        await createTrackerComment(version, `Не удалось удалить пакет ${version}`);
    }
}

async function getPullRequestData(id) {
    let result;

    try {
        result = await fetch(`${ApiHosts.GITHUB}/repos/${CONNECT_REPOSITORY}/pulls/${id}`, {
            method: 'GET',
            headers: {
                Authorization: `OAuth ${CONNECT_GITHUB_OAUTH_TOKEN}`,
            },
        })
            .then(res => res.json());
    } catch (e) {
        console.error(`Не удалось загрузить данные о пулреквесте #${id}`, e);
    }

    return result;
}

async function onPullRequestUpdate(id) {
    const { state, head: { ref: branchName } } = await getPullRequestData(id);

    console.log(`Данные пулреквеста #${id}: state=${state} branch=${branchName}`);

    if (state === 'merged' || state === 'closed') {
        await removeEnv(branchName);

        await removeDockerPackage(branchName);
    }
}

(async() => {
    if (TRENDBOX_PULL_REQUEST_NUMBER) {
        console.log('RUN: onPullRequestUpdate', TRENDBOX_PULL_REQUEST_NUMBER);
        await onPullRequestUpdate(TRENDBOX_PULL_REQUEST_NUMBER);
    }
})();
