import { type Express } from "express";
import fs from "fs";
import { type Server } from "http";
import path from "path";
import { createServer as createViteServer } from "vite";
import { nanoid } from "nanoid";
import viteConfig from "../../vite.config";

const root = process.cwd();

/**
 * VITE (DEV ONLY)
 *
 * Only ever imported from `dev.ts`, which is run directly via `tsx` and is
 * NOT part of the esbuild production bundle — so importing `vite` and
 * `vite.config` (which itself imports devDependency-only plugins) here is
 * safe.
 */
export async function setupVite(app: Express, server: Server) {
  const vite = await createViteServer({
    ...viteConfig,
    configFile: false,
    server: {
      middlewareMode: true,
      hmr: { server },
    },
    appType: "custom",
  });

  app.use(vite.middlewares);

  app.use("*", async (req, res, next) => {
    try {
      const url = req.originalUrl;

      const indexPath = path.resolve(root, "client", "index.html");

      let template = await fs.promises.readFile(indexPath, "utf-8");

      template = template.replace(
        `src="/src/main.tsx"`,
        `src="/src/main.tsx?v=${nanoid()}"`
      );

      const html = await vite.transformIndexHtml(url, template);

      res.status(200).set({ "Content-Type": "text/html" }).end(html);
    } catch (err) {
      vite.ssrFixStacktrace(err as Error);
      next(err);
    }
  });
}
