"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var login_command_exports = {};
__export(login_command_exports, {
  LoginCommand: () => LoginCommand
});
module.exports = __toCommonJS(login_command_exports);
var client = __toESM(require("@botpress/client"));
var fs = __toESM(require("fs"));
var paging = __toESM(require("../api/paging"));
var consts = __toESM(require("../consts"));
var errors = __toESM(require("../errors"));
var import_global_command = require("./global-command");
class LoginCommand extends import_global_command.GlobalCommand {
  async run() {
    let profileName = consts.defaultProfileName;
    if (this.argv.profile) {
      let profileExists = false;
      if (fs.existsSync(this.globalPaths.abs.profilesPath)) {
        const profiles = await this.readProfilesFromFS();
        profileExists = profiles[this.argv.profile] !== void 0;
      }
      if (profileExists) {
        const overwrite = await this.prompt.confirm(
          `This command will overwrite the existing profile '${this.argv.profile}'. Do you want to continue?`
        );
        if (!overwrite) throw new errors.AbortedOperationError();
      } else {
        this.logger.log(`This command will create new profile '${this.argv.profile}'`, { prefix: "\u2139\uFE0E" });
      }
      profileName = this.argv.profile;
    }
    const promptedToken = await this.globalCache.sync("token", this.argv.token, async (previousToken) => {
      const prompted = await this.prompt.text("Enter your Personal Access Token", {
        initial: previousToken
      });
      if (!prompted) {
        throw new errors.ParamRequiredError("Personal Access Token");
      }
      return prompted;
    });
    if (this.argv.apiUrl !== consts.defaultBotpressApiUrl) {
      this.logger.log(`Using custom api url ${this.argv.apiUrl} to try fetching workspaces`, { prefix: "\u{1F517}" });
    }
    const promptedWorkspaceId = await this.globalCache.sync("workspaceId", this.argv.workspaceId, async (defaultId) => {
      const tmpClient = new client.Client({ apiUrl: this.argv.apiUrl, token: promptedToken });
      const userWorkspaces = await paging.listAllPages(tmpClient.listWorkspaces, (r) => r.workspaces).catch((thrown) => {
        throw errors.BotpressCLIError.wrap(thrown, "Could not list workspaces");
      });
      if (userWorkspaces.length === 0) {
        throw new errors.NoWorkspacesFoundError();
      }
      const initial = userWorkspaces.find((ws) => ws.id === defaultId);
      const prompted = await this.prompt.select("Which workspace do you want to login to?", {
        initial: initial && { title: initial.name, value: initial.id },
        choices: userWorkspaces.map((ws) => ({ title: ws.name, value: ws.id }))
      });
      if (!prompted) {
        throw new errors.ParamRequiredError("Workspace Id");
      }
      return prompted;
    });
    await this.globalCache.set("apiUrl", this.argv.apiUrl);
    const api = this.api.newClient(
      { apiUrl: this.argv.apiUrl, token: promptedToken, workspaceId: promptedWorkspaceId },
      this.logger
    );
    await api.testLogin().catch((thrown) => {
      throw errors.BotpressCLIError.wrap(thrown, "Login failed. Please check your credentials");
    });
    await this.writeProfileToFS(profileName, {
      apiUrl: this.argv.apiUrl,
      token: promptedToken,
      workspaceId: promptedWorkspaceId
    });
    this.logger.success("Logged In");
  }
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  LoginCommand
});
//# sourceMappingURL=login-command.js.map
