import type { Command } from "commander";
import { printStandloneInitialBanner } from "../../utilities/initialBanner.js";
import {
  CommonCommandOptions,
  commonOptions,
  handleTelemetry,
  OutroCommandError,
  wrapCommandAction,
} from "../../cli/common.js";
import { login } from "../login.js";
import { loadConfig } from "../../config.js";
import { resolve } from "path";
import { getProjectClient } from "../../utilities/session.js";
import { logger } from "../../utilities/logger.js";
import { z } from "zod";
import { intro, isCancel, outro, text } from "@clack/prompts";

const WorkersCreateCommandOptions = CommonCommandOptions.extend({
  env: z.enum(["prod", "staging"]),
  config: z.string().optional(),
  projectRef: z.string().optional(),
});
type WorkersCreateCommandOptions = z.infer<typeof WorkersCreateCommandOptions>;

export function configureWorkersCreateCommand(program: Command) {
  return commonOptions(
    program
      .command("create")
      .description("List all available workers")
      .argument("[path]", "The path to the project", ".")
      .option(
        "-e, --env <env>",
        "Deploy to a specific environment (currently only prod and staging are supported)",
        "prod"
      )
      .option("-c, --config <config file>", "The name of the config file, found at [path]")
      .option(
        "-p, --project-ref <project ref>",
        "The project ref. Required if there is no config file. This will override the project specified in the config file."
      )
      .action(async (path, options) => {
        await handleTelemetry(async () => {
          await printStandloneInitialBanner(true, options.profile);
          await workersCreateCommand(path, options);
        });
      })
  );
}

async function workersCreateCommand(dir: string, options: unknown) {
  return await wrapCommandAction(
    "workerCreateCommand",
    WorkersCreateCommandOptions,
    options,
    async (opts) => {
      return await _workersCreateCommand(dir, opts);
    }
  );
}

async function _workersCreateCommand(dir: string, options: WorkersCreateCommandOptions) {
  intro("Creating new worker group");

  const authorization = await login({
    embedded: true,
    defaultApiUrl: options.apiUrl,
    profile: options.profile,
    silent: true,
  });

  if (!authorization.ok) {
    if (authorization.error === "fetch failed") {
      throw new Error(
        `Failed to connect to ${authorization.auth?.apiUrl}. Are you sure it's the correct URL?`
      );
    } else {
      throw new Error(
        `You must login first. Use the \`login\` CLI command.\n\n${authorization.error}`
      );
    }
  }

  const projectPath = resolve(process.cwd(), dir);

  const resolvedConfig = await loadConfig({
    cwd: projectPath,
    overrides: { project: options.projectRef },
    configFile: options.config,
  });

  logger.debug("Resolved config", resolvedConfig);

  const projectClient = await getProjectClient({
    accessToken: authorization.auth.accessToken,
    apiUrl: authorization.auth.apiUrl,
    projectRef: resolvedConfig.project,
    env: options.env,
    profile: options.profile,
  });

  if (!projectClient) {
    throw new Error("Failed to get project client");
  }

  const name = await text({
    message: "What would you like to call the new worker?",
    placeholder: "<auto-generated>",
  });

  if (isCancel(name)) {
    throw new OutroCommandError();
  }

  const description = await text({
    message: "What is the purpose of this worker?",
    placeholder: "<none>",
  });

  if (isCancel(description)) {
    throw new OutroCommandError();
  }

  const newWorker = await projectClient.client.workers.create({
    name,
    description,
  });

  if (!newWorker.success) {
    throw new Error(`Failed to create worker: ${newWorker.error}`);
  }

  outro(
    `Successfully created worker ${newWorker.data.workerGroup.name} with token ${newWorker.data.token.plaintext}`
  );
}
