import { existsSync, readFileSync } from "node:fs";
import { createServer } from "node:https";
import path from "node:path";
import { fileURLToPath } from "node:url";
import next from "next";

const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
const dir = path.join(root, "apps/web");
const hostname = process.env.WEB_HOST ?? "0.0.0.0";
const port = Number(process.env.WEB_PORT ?? 3000);
const keyPath = process.env.HTTPS_KEY_PATH ?? path.join(root, "certs/inventory2026-local.key");
const certPath = process.env.HTTPS_CERT_PATH ?? path.join(root, "certs/inventory2026-local.pem");

if (!existsSync(keyPath) || !existsSync(certPath)) {
  console.error(`Missing HTTPS certificate files:
  ${keyPath}
  ${certPath}`);
  process.exit(1);
}

const app = next({ dev: false, dir, hostname, port });
const handle = app.getRequestHandler();

await app.prepare();

createServer(
  {
    key: readFileSync(keyPath),
    cert: readFileSync(certPath)
  },
  (request, response) => handle(request, response)
).listen(port, hostname, () => {
  console.log(`SSS Inventory web listening at https://${hostname}:${port}`);
});
