#!/usr/bin/env node

import { Command } from "commander";
import { startWithout } from "@digiresilience/montar";
import { migrateWrapper } from "@digiresilience/metamigo-db";
import { loadConfig } from "@digiresilience/metamigo-config";
import { genConf, listConfig } from "./config.js";
import { createTokenForTesting, generateJwks } from "./jwks.js";
import { exportGraphqlSchema } from "./metamigo-postgraphile.js";
import "@digiresilience/metamigo-api";
import "@digiresilience/metamigo-worker";

const program = new Command();

export async function runServer(): Promise<void> {
  await startWithout(["worker"]);
}

export async function runWorker(): Promise<void> {
  await startWithout(["server"]);
}

program
  .command("config-generate")
  .description("Generate a sample JSON configuration file (to stdout)")
  .action(genConf);

program
  .command("config-help")
  .description("Prints the entire convict config ")
  .action(listConfig);

program
  .command("api")
  .description("Run the application api server")
  .action(runServer);

program
  .command("worker")
  .description("Run the worker to process jobs")
  .action(runWorker);

program
  .command("db <commands...>")
  .description("Run graphile-migrate commands with your app's config loaded.")
  .action(async (args) => {
    const config = await loadConfig();
    return migrateWrapper(args, config);
  });

program
  .command("gen-jwks")
  .description("Generate the JWKS")
  .action(generateJwks);

program
  .command("gen-testing-jwt")
  .description("Generate a JWT for the test suite")
  .action(createTokenForTesting);

program
  .command("export-graphql-schema")
  .description("Export the graphql schema")
  .action(exportGraphqlSchema);

program.parse(process.argv);
