import { resolve } from "node:path";
import { readProviderAppsConfig } from "./config";
import { readProviderRelease, releaseResponse } from "./release";

if (process.argv.length !== 2) throw new Error("Provider Apps server does not accept startup arguments");

const repositoryRoot = resolve(import.meta.dir, "../../..");
const config = readProviderAppsConfig(repositoryRoot);
const release = readProviderRelease(repositoryRoot, config);
const server = Bun.serve({
  hostname: config.runtime.bindHost,
  port: config.runtime.port,
  fetch(request) {
    const url = new URL(request.url);
    return releaseResponse(request.method, url.pathname, config, release, url.origin);
  },
});

console.log(JSON.stringify({
  event: "provider-apps.started",
  target: config.target.id,
  bind: `${server.hostname}:${server.port}`,
  publicBaseUrl: config.publicExposure.publicBaseUrl,
  latestVersion: release.manifest.latestVersion,
}));

function shutdown(signal: string): void {
  console.log(JSON.stringify({ event: "provider-apps.stopping", signal }));
  server.stop(true);
  process.exit(0);
}

process.on("SIGINT", () => shutdown("SIGINT"));
process.on("SIGTERM", () => shutdown("SIGTERM"));
