import express, { type Router } from "express";
import fs from "fs";
import path from "path";

const root = process.cwd();

/**
 * STATIC (PRODUCTION)
 *
 * Serves the built SPA from dist/public onto the given router. This
 * module must NOT import anything from `vite` (or vite.config, which
 * itself imports several devDependencies). Those packages are not
 * installed in production (`npm install` on cPanel only installs
 * `dependencies`), and a top-level ESM import of a missing package
 * crashes the whole process before the server can even start
 * (ERR_MODULE_NOT_FOUND).
 *
 * The caller is expected to mount this router both at "/" and under any
 * configured BASE_PATH (e.g. "/app"), so paths here are always relative
 * to whichever mount point is in effect.
 *
 * REVISÃO (jul/2026): este arquivo NÃO gera mais Open Graph dinâmico.
 * Essa responsabilidade saiu pra server/_core/share.ts, nas rotas
 * /share/episodio/:id e /share/faixa/:id — HTML mínimo, sem carregar
 * este index.html nem o bundle do Vite. Motivo: reescrever as meta tags
 * do próprio index.html a cada requisição significava ler o arquivo do
 * disco toda vez e (pior) fazer consultas ao banco dentro do caminho de
 * quem só queria o app — inclusive pra humanos, que não precisam disso.
 * Ver server/_core/share.ts para o histórico completo da decisão.
 *
 * Como não há mais nada dinâmico aqui, o index.html é lido do disco UMA
 * vez, no boot — não a cada requisição.
 */

export function serveStatic(app: Router) {
  const distPath = path.resolve(root, "dist", "public");

  if (!fs.existsSync(distPath)) {
    console.error("[STATIC] Build não encontrado:", distPath);
  }

  const indexFile = path.resolve(distPath, "index.html");
  const indexHtml = fs.existsSync(indexFile) ? fs.readFileSync(indexFile, "utf-8") : null;

  app.use(express.static(distPath));

  app.use("*", (_req, res) => {
    if (!indexHtml) {
      return res.status(500).send("index.html não encontrado no build");
    }

    res.set("Content-Type", "text/html");
    res.set("Cache-Control", "no-cache, no-store, must-revalidate");
    res.send(indexHtml);
  });
}
