import axios                      from 'axios';
import SharedConfig               from '../config/SharedConfig';
import * as GitlabCore            from '@gitbeaker/core';
import { Gitlab, PipelineSchema } from '@gitbeaker/rest';
import GitlabToken                from '../types/Gitlab/GitlabToken';


class SharedGitlabManager {
    private api!: GitlabCore.Gitlab<false>;

    setToken(token: string) {
        this.api = new Gitlab({
                                  host : SharedConfig.gitlab.URL,
                                  token: token
                              });
    }

    constructor(token: string) {
        this.setToken(token);
    }

    async getTokens(codeOrRefresh: string, isRefresh: boolean = false, clientSecret: string = ''): Promise<GitlabToken> {
        const response = await axios.post<GitlabToken>(SharedConfig.login.gitlab.url.token, {
            client_id    : SharedConfig.login.gitlab.client.id,
            client_secret: clientSecret,
            grant_type   : isRefresh ? 'refresh_token' : 'authorization_code',
            refresh_token: codeOrRefresh,
            code         : codeOrRefresh,
            redirect_uri : SharedConfig.login.gitlab.url.redirect
        });

        return response.data;
    }

    async getRepositoryPipelines(repoId: number, branch: string = 'main'): Promise<Array<PipelineSchema>> {
        return await this.api.Pipelines.all(repoId, {
            ref: branch
        });
    }
}


export default SharedGitlabManager;