import { existsSync } from "node:fs";
import { spawn } from "node:child_process";
import { resolve } from "node:path";
import { loadConfig } from "../src/config.ts";

const config = loadConfig();
const dbgateBin = resolve("node_modules/.bin/dbgate-serve.cmd");
const command = existsSync(dbgateBin) ? dbgateBin : "dbgate-serve";
const host = config.database.host || "127.0.0.1";
const port = String(config.database.port || 3306);
const user = config.database.user || "root";
const password = config.database.password || "";
const catalogDatabase = config.database.name || "9bplus";
const scrapeDatabase = config.database.scrapeName || "catalog_scrape";
const dbgateUrl = new URL(config.dbGate.url || "http://127.0.0.1:3000");

const env = {
  ...process.env,
  PORT: dbgateUrl.port || "3000",
  SKIP_ALL_AUTH: "1",
  CONNECTIONS: "local_9bplus,local_scrape",
  ENGINE_local_9bplus: "mysql@dbgate-plugin-mysql",
  LABEL_local_9bplus: "Local 9bplus DB",
  SERVER_local_9bplus: host,
  PORT_local_9bplus: port,
  USER_local_9bplus: user,
  PASSWORD_local_9bplus: password,
  DATABASE_local_9bplus: catalogDatabase,
  ENGINE_local_scrape: "mysql@dbgate-plugin-mysql",
  LABEL_local_scrape: "Local scrape DB",
  SERVER_local_scrape: host,
  PORT_local_scrape: port,
  USER_local_scrape: user,
  PASSWORD_local_scrape: password,
  DATABASE_local_scrape: scrapeDatabase,
};

console.log(`Starting DBGate at ${dbgateUrl.origin}`);
console.log(`Configured connections: Local 9bplus DB, Local scrape DB`);

const child = spawn(command, [], {
  env,
  stdio: "inherit",
  shell: true,
});

child.on("exit", (code, signal) => {
  if (signal) {
    process.kill(process.pid, signal);
    return;
  }

  process.exit(code ?? 0);
});
