import { cpSync, existsSync } from "node:fs";
import { spawn } from "node:child_process";
import { resolve } from "node:path";

// `output: "standalone"` in next.config.ts produces .next/standalone/server.js
// but Next deliberately leaves public/ and .next/static out of the bundle so
// they can be served by a CDN. The minimal server.js also does NOT auto-load
// .env / .env.local the way `next start` does, so for local QA we both copy
// the static assets into the bundle and pass --env-file flags through.
//
// Coolify's deploy uses .next/standalone directly and injects env vars via
// the platform, so this script is only invoked via `pnpm start` for local
// runs and never on production.

const root = resolve(import.meta.dirname, "..");
const standalone = resolve(root, ".next/standalone");
const serverEntry = resolve(standalone, "server.js");

if (!existsSync(serverEntry)) {
  console.error(
    "[start-standalone] .next/standalone/server.js missing — run `pnpm build` first.",
  );
  process.exit(1);
}

cpSync(resolve(root, "public"), resolve(standalone, "public"), {
  recursive: true,
});
cpSync(
  resolve(root, ".next/static"),
  resolve(standalone, ".next/static"),
  { recursive: true },
);

const envArgs = [];
const envLocal = resolve(root, ".env.local");
const envFile = resolve(root, ".env");
if (existsSync(envFile)) envArgs.push(`--env-file=${envFile}`);
if (existsSync(envLocal)) envArgs.push(`--env-file=${envLocal}`);

const child = spawn(process.execPath, [...envArgs, serverEntry], {
  stdio: "inherit",
  env: process.env,
});
child.on("exit", (code) => process.exit(code ?? 0));
