import AppConfig from "./appConfig.js";
import constants from "./constants.js";
import RESTClient from "./restClient.js";
export default class CloudLoginManager {
    _APP_CONFIG_SCOPE_NAME = 'cloud';
    apiToken;
    username;
    getUserString() {
        return this.username || "(none)";
    }
    hasCredentials() {
        return Boolean(this.username && this.apiToken);
    }
    async login() {
        await this.loadCredentials();
        if (!this.apiToken || !this.username) {
            throw new Error(`This operation requires you to log into Kyndryl Cloud Uplift first. Please try \`${constants.APP_NAME} cloud login --help\`.`);
        }
        try {
            const restClient = new RESTClient(constants.CLOUD_TEST_ENDPOINT);
            await restClient.call({
                auth: {
                    password: this.apiToken,
                    username: this.username
                },
                method: 'head'
            });
        }
        catch (error) {
            if (error instanceof Error) {
                // eslint-disable-next-line unicorn/prefer-type-error
                throw new Error(`Login failed: ${error.message}. Please check your credentials and try again.`);
            }
            throw error;
        }
    }
    async logout() {
        this.username = undefined;
        this.apiToken = undefined;
        await this.flushCredentials();
    }
    async setCredentials(apiToken, username) {
        this.apiToken = apiToken;
        this.username = username;
        await this.flushCredentials();
    }
    async flushCredentials() {
        const appConfig = await AppConfig.getInstance();
        appConfig.setConfig("username", this.username, this._APP_CONFIG_SCOPE_NAME);
        appConfig.setConfig("apiToken", this.apiToken, this._APP_CONFIG_SCOPE_NAME);
    }
    async loadCredentials() {
        if (this.username && this.apiToken) {
            return;
        }
        const appConfig = await AppConfig.getInstance();
        this.username = await appConfig.getConfig("username", this._APP_CONFIG_SCOPE_NAME);
        this.apiToken = await appConfig.getConfig("apiToken", this._APP_CONFIG_SCOPE_NAME);
    }
}
