/* eslint-disable @typescript-eslint/no-explicit-any */
import { AxiosError } from 'axios';
import constants from './constants.js';
import LoginManager from './loginManager.js';
import RESTClient from './restClient.js';
export default class CSSClient {
    restClient;
    async delete(path) {
        return this.call({ method: 'delete', path });
    }
    async get(path, params) {
        return this.call({ method: 'get', params, path });
    }
    async post(path, data) {
        return this.call({ data, method: 'post', path });
    }
    async put(path, data) {
        return this.call({ data, method: 'put', path });
    }
    async call(callParams) {
        let error;
        for (const forceLogin of [false, true]) {
            try {
                const loginManager = new LoginManager();
                // eslint-disable-next-line no-await-in-loop
                const token = await loginManager.login(forceLogin);
                // Get the CSS root from saved credentials or fall back to constant/env var
                if (!this.restClient) {
                    // eslint-disable-next-line no-await-in-loop
                    const cssRoot = await loginManager.getCssRoot();
                    const baseUrl = process.env.CSS_SERVICE_ENDPOINT || cssRoot || constants.CSS_ROOT;
                    this.restClient = new RESTClient(baseUrl);
                }
                callParams.headers = { Authorization: `Bearer ${token}` };
                // eslint-disable-next-line no-await-in-loop
                return await this.restClient.call(callParams);
            }
            catch (error_) {
                if (!(error_ instanceof AxiosError && error_.response?.status === 401)) {
                    error = error_;
                    break;
                }
            }
        }
        throw (error || new Error(`Failed to make ${callParams.method.toUpperCase()} request to ${callParams.path}`));
    }
}
