import { createApp } from "./createApp";
import { serveStatic } from "./static";
import { registerShareRoutes } from "./share";
import { findAvailablePort } from "./port";
import { ENV } from "./env";

/**
 * PRODUCTION ENTRY POINT.
 *
 * This is the file esbuild bundles into `dist/index.js` (see the "build"
 * script in package.json). It must never import `vite`, `vite.config`, or
 * anything that transitively imports them — those are devDependencies and
 * are not installed by `npm install` on cPanel, so a static (or even
 * dynamic-but-bundled) import of them crashes the process at startup with
 * ERR_MODULE_NOT_FOUND before the server can even bind to a port.
 *
 * The dev server (with Vite middleware) lives in `dev.ts`, which is run
 * directly via `tsx` (not bundled) and is therefore free to use Vite.
 */
async function startServer() {
  const { app, server, coreRouter } = createApp();

  // IMPORTANT: registrar ANTES de serveStatic — este último registra um
  // catch-all "*" que responderia (errado) a qualquer rota /share/* se
  // viesse primeiro.
  registerShareRoutes(coreRouter);
  serveStatic(coreRouter);

  // IMPORTANT: register the more specific BASE_PATH mount FIRST. Express
  // tries middleware in registration order, and "/" matches every path —
  // if it were registered first it would swallow "/app/*" requests too
  // (passing the full "/app/..." path through unmodified, where nothing
  // inside coreRouter matches it except the SPA catch-all).
  if (ENV.basePath) {
    app.use(ENV.basePath, coreRouter);
  }
  app.use("/", coreRouter);

  const preferredPort = parseInt(process.env.PORT || "3000");
  const port = await findAvailablePort(preferredPort);

  if (port !== preferredPort) {
    console.log(`Port ${preferredPort} is busy, using port ${port} instead`);
  }

  server.listen(port, () => {
    console.log(`Server running on http://localhost:${port}/`);
  });
}

startServer().catch(console.error);
