/**
 * Builds a cPanel upload archive (source + .next, without node_modules).
 *
 * Usage:
 *   npm run build
 *   npm run cpanel:package
 *
 * Then upload dist/cpanel-deploy.zip to the server and extract into the
 * Node.js application root. Run `npm ci --omit=dev` on the Linux server
 * so native modules (better-sqlite3, sharp) match the host.
 */
const fs = require("fs");
const path = require("path");
const { execFileSync } = require("child_process");

const root = path.resolve(__dirname, "..");
const distDir = path.join(root, "dist");
const zipPath = path.join(distDir, "cpanel-deploy.zip");
const buildIdPath = path.join(root, ".next", "BUILD_ID");

if (!fs.existsSync(buildIdPath)) {
  console.error(
    "Missing .next/BUILD_ID. Run `npm run build` before packaging.",
  );
  process.exit(1);
}

fs.mkdirSync(distDir, { recursive: true });
if (fs.existsSync(zipPath)) {
  fs.unlinkSync(zipPath);
}

const excludeGlobs = [
  "node_modules/*",
  ".git/*",
  "data/*",
  "dist/*",
  "out/*",
  "coverage/*",
  ".next/dev/*",
  ".next/cache/*",
  ".next/diagnostics/*",
  ".next/trace",
  ".next/trace-build",
  ".env",
  ".env.local",
  ".env.production",
  ".env*.local",
  "*.db",
  "*.db-journal",
  "app.zip",
  "dist/cpanel-deploy.zip",
];

const includeHints = [
  "package.json",
  "package-lock.json",
  "index.js",
  "next.config.ts",
  "tsconfig.json",
  "postcss.config.mjs",
  "prisma.config.ts",
  "proxy.ts",
  ".node-version",
  ".env.example",
  "app",
  "prisma",
  "public",
  ".next",
  "scripts",
];

function pathExists(rel) {
  return fs.existsSync(path.join(root, rel));
}

const presentIncludes = includeHints.filter(pathExists);
if (!presentIncludes.includes("public") && !pathExists("public")) {
  // public/ is optional
}

console.log("Packaging for cPanel upload...");
console.log("Includes:", presentIncludes.join(", "));

const isWindows = process.platform === "win32";

try {
  if (isWindows) {
    // Prefer tar.exe (Windows 10+) which creates zip via -a
    const args = [
      "-a",
      "-c",
      "-f",
      zipPath,
      ...excludeGlobs.flatMap((g) => ["--exclude", g]),
      ...presentIncludes,
    ];
    execFileSync("tar", args, { cwd: root, stdio: "inherit" });
  } else {
    const args = [
      "-r",
      zipPath,
      ...excludeGlobs.flatMap((g) => ["-x", g]),
      ...presentIncludes,
    ];
    execFileSync("zip", args, { cwd: root, stdio: "inherit" });
  }
} catch (error) {
  console.error(
    "Failed to create zip. On Windows ensure tar.exe is available;",
    "on Linux/macOS install zip.",
  );
  console.error(error instanceof Error ? error.message : error);
  process.exit(1);
}

const sizeMb = (fs.statSync(zipPath).size / (1024 * 1024)).toFixed(1);
console.log(`\nCreated ${zipPath} (${sizeMb} MB)`);
console.log(`
Next steps:
1. Upload and extract into your cPanel Node.js app root (NOT public_html alone).
2. In Terminal: npm ci --omit=dev
3. Create .env from .env.example (or set vars in Setup Node.js App).
4. npm run db:setup
5. Restart the Node.js app in cPanel.
See CPANEL.md for the full checklist.
`);
