"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.GitlabApi = void 0;
const axios_1 = __importDefault(require("axios"));
const utils_1 = require("../../utils");
class GitlabApi {
    constructor({ token, baseUrl, vcsId, maxFileSize, }) {
        if (!token)
            throw new utils_1.ErrorWithCode(400, 'Token is required');
        this.token = token;
        this.baseUrl = baseUrl;
        this.vcsId = vcsId;
        this.maxFileSize = maxFileSize;
    }
    getProjectId(repository) {
        return repository.projectId;
    }
    getRequestHeaders() {
        return {
            Authorization: `Bearer ${this.token}`,
        };
    }
    getRepositories() {
        return axios_1.default
            .get(this.baseUrl, {
            headers: this.getRequestHeaders(),
            params: {
                owned: true,
            },
        })
            .then((response) => {
            return response.data.reduce((acc, repositoryData) => {
                acc[repositoryData.name] = {
                    name: repositoryData.name,
                    webUrl: `${repositoryData.web_url}`,
                    projectId: repositoryData.id.toString(),
                    defaultBranch: repositoryData.default_branch,
                    vcsId: this.vcsId,
                };
                return acc;
            }, {});
        });
    }
    getBranches({ repository }) {
        return axios_1.default
            .get(`${this.baseUrl}/${this.getProjectId(repository)}/repository/branches`, {
            headers: this.getRequestHeaders(),
        })
            .then((response) => {
            return response.data.map((i) => i.name);
        });
    }
    getRepositoryContent({ repository, branch, path = '', }) {
        return axios_1.default
            .get(`${this.baseUrl}/${this.getProjectId(repository)}/repository/tree?path=${path}`, {
            headers: this.getRequestHeaders(),
            params: {
                ref_name: branch,
            },
        })
            .then((response) => {
            return response.data.map((item) => {
                return {
                    name: item.name,
                    type: item.type === 'tree' ? 'dir' : 'file',
                    url: `/-/blob/${branch}/${item.name}`,
                };
            });
        });
    }
    async getFileContent({ repository, branch, path, }) {
        const response = await axios_1.default.get(`${this.baseUrl}/${this.getProjectId(repository)}/repository/files/${path}/raw`, {
            headers: this.getRequestHeaders(),
            params: {
                ref_name: branch,
            },
            responseType: 'stream',
        });
        const fileStream = response.data;
        return await new Promise((resolve, reject) => {
            let temp = '';
            fileStream.on('data', (chunk) => {
                temp += chunk.toString();
                if (Buffer.byteLength(temp) > this.maxFileSize)
                    reject(new Error(`File is too big. Max size ${this.maxFileSize}Mb`));
            });
            fileStream.on('end', () => {
                resolve(temp);
            });
            fileStream.on('error', (err) => {
                reject(err);
            });
        });
    }
}
exports.GitlabApi = GitlabApi;
