import { Command } from "commander";
import chalk from "chalk";
import { readProjectConfig } from "./lib/config.js";
import open from "open";
import axios from "axios";
import { version } from "../index.js";
import { fatalServerErr } from "./lib/utils.js";
import { getUrlAndAdminKey } from "./lib/api.js";
import { Context, oneoffContext } from "./lib/context.js";

/** Pull the local config and overwrite the remote one. */
export const dashboard = new Command("dashboard")
  .description("Open the dashboard in the browser")
  .option(
    "--no-open",
    "Don't automatically open the dashboard in the default browser"
  )
  .action(async options => {
    const ctx = oneoffContext;
    const { projectConfig } = await readProjectConfig(ctx);
    const { url, adminKey } = await getUrlAndAdminKey(
      ctx,
      projectConfig.project,
      projectConfig.team,
      "prod"
    );
    const loginUrl = await dashboardLogin(ctx, url, adminKey);

    if (options.open) {
      console.log(chalk.gray(`Opening ${loginUrl} in the default browser...`));
      await open(loginUrl);
    } else {
      console.log(loginUrl);
    }
  });

async function dashboardLogin(
  ctx: Context,
  instanceOrigin: string,
  adminKey: string
): Promise<string> {
  try {
    return (
      await axios.post(`${instanceOrigin}/api/${version}/one_time_login_url`, {
        version,
        adminKey,
      })
    ).data.loginUrl;
  } catch (err) {
    console.error(
      chalk.red("Error: Unable to login to dashboard at ", instanceOrigin)
    );
    return await fatalServerErr(ctx, err);
  }
}
