import { select } from "@inquirer/prompts";
import axios from "axios";
import { ResolvedEmbeddableConfig } from "./defineConfig";
import { Options, Ora } from "ora";

export async function getWorkspaces(
  ctx: ResolvedEmbeddableConfig,
  token: string,
  workspaceSpinner: Ora,
) {
  try {
    const response = await axios.get(`${ctx.pushBaseUrl}/workspace`, {
      headers: {
        Authorization: `Bearer ${token}`,
      },
    });

    return response.data?.filter((w: any) => !w.devWorkspace);
  } catch (e: any) {
    if (ctx.dev?.watch) {
      workspaceSpinner.stop();
      throw e;
    }
    if (e.response?.status === 401) {
      workspaceSpinner.fail(
        'Unauthorized. Please login using "npm run embeddable:login"',
      );
    } else {
      workspaceSpinner.fail("Failed to fetch workspaces");
    }
    process.exit(1);
  }
}

export async function selectWorkspace(
  ora: (options?: string | Options) => Ora,
  ctx: ResolvedEmbeddableConfig,
  token: string,
) {
  const workspaceSpinner = ora({
    text: `Fetching workspaces using ${ctx.pushBaseUrl}...`,
    color: "green",
    discardStdin: false,
  }).start();

  const availableWorkspaces = await getWorkspaces(ctx, token, workspaceSpinner);

  let selectedWorkspace;

  if (availableWorkspaces.length === 0) {
    workspaceSpinner.fail("No workspaces found");
    process.exit(1);
  }

  workspaceSpinner.info(`Found ${availableWorkspaces.length} workspace(s)`);

  const isDev = ctx.dev?.watch;

  if (availableWorkspaces.length === 1) {
    selectedWorkspace = availableWorkspaces[0];
  } else {
    selectedWorkspace = await select({
      message: isDev
        ? "Select workspace to use as primary"
        : "Select workspace to push changes",
      choices: availableWorkspaces.map((workspace: any) => ({
        name: `${workspace.name} (${workspace.workspaceId})`,
        value: workspace,
      })),
    });
  }

  workspaceSpinner.succeed(
    `Workspace: ${selectedWorkspace.name} (${selectedWorkspace.workspaceId})`,
  );

  return selectedWorkspace;
}
