/**
 * postbuild-standalone.mjs — make the Next standalone bundle self-serving.
 *
 * `next build` with `output: 'standalone'` emits `.next/standalone/server.js`
 * but deliberately does NOT copy `.next/static` or `public/` into it. The
 * standalone server resolves both relative to its OWN directory, so without
 * this copy a global install renders with no CSS, no JS chunks, and broken
 * images. We copy them in so the bundle shipped via the package `files`
 * whitelist (`.next/standalone/`) is complete and self-contained.
 *
 * Idempotent: removes the destinations first, then copies fresh.
 */

import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';

const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const STANDALONE = path.join(ROOT, '.next', 'standalone');

function copyInto(srcRel, destRel) {
  const src = path.join(ROOT, srcRel);
  const dest = path.join(STANDALONE, destRel);
  if (!fs.existsSync(src)) {
    console.warn(`[postbuild] skip ${srcRel} — not found`);
    return;
  }
  fs.rmSync(dest, { recursive: true, force: true });
  fs.mkdirSync(path.dirname(dest), { recursive: true });
  fs.cpSync(src, dest, { recursive: true });
  console.log(`[postbuild] copied ${srcRel} → .next/standalone/${destRel}`);
}

if (!fs.existsSync(STANDALONE)) {
  console.warn('[postbuild] .next/standalone not found — did `next build` run with output:"standalone"?');
  process.exit(0);
}

copyInto(path.join('.next', 'static'), path.join('.next', 'static'));
copyInto('public', 'public');

for (const envName of ['.env', '.env.local', '.env.development', '.env.production', '.env.test']) {
  const envPath = path.join(STANDALONE, envName);
  if (fs.existsSync(envPath)) {
    fs.rmSync(envPath, { force: true });
    console.log(`[postbuild] removed ${path.join('.next', 'standalone', envName)} from publish bundle`);
  }
}

console.log('[postbuild] standalone bundle is self-serving.');
