/* eslint-disable no-console */
const fetch = require('node-fetch');

const registryHost = 'https://registry.yandex.net';

class RegistryApi {
    constructor(options) {
        if (!options.token) {
            throw new Error('Please provide oauth token with { token: VALUE }');
        }

        this.options = options;
    }

    request({ method = 'GET', path }) {
        return fetch(`${registryHost}/v2/${this.options.repo}/${path}`, {
            method,
            headers: {
                Authorization: `OAuth ${this.options.token}`,
                Accept: 'application/vnd.docker.distribution.manifest.v2+json',
            },
        });
    }

    getPackages() {
        return this.request({ path: 'tags/list' })
            .then(res => res.json())
            .then(data => data.tags);
    }

    getHash(version) {
        return this.request({ path: `manifests/${version}` })
            .then(response => response.headers.get('docker-content-digest'));
    }

    async remove(version) {
        try {
            const tags = await this.getPackages();

            if (!tags.includes(version)) {
                console.error(`Не удалось найти пакет с версией ${version}`);

                return;
            }

            const hash = await this.getHash(version);

            await this.request({ method: 'DELETE', path: `manifests/${hash}` });

            console.log(`Удален пакет ${registryHost}/${this.options.repo}:${version}`);
        } catch (e) {
            console.error(`Не удалось удалить пакет ${registryHost}/${this.options.repo}:${version}`, e);
            throw e;
        }
    }
}

module.exports = RegistryApi;
