import { readFileSync } from "node:fs";
import { resolve } from "node:path";
import {
  createOrderlySsrContext,
  renderOrderlySsrHtml,
  sourceHtmlFileForUrl
} from "./ssr.mjs";

export function orderlySsrDevServer(options = {}) {
  const root = resolve(options.root ?? process.cwd());
  const enabled = options.enabled ?? (process.env.ORDERLY_DEV_SSR !== "0" && !process.argv.includes("--no-ssr"));
  let contextPromise;
  return {
    name: "orderly-ssr-dev-server",
    configureServer(server) {
      server.middlewares.use(async (request, response, next) => {
        const file = sourceHtmlFileForUrl(root, request.url ?? "/");
        if (!file) {
          next();
          return;
        }

        try {
          const url = new URL(request.url ?? "/", "http://localhost");
          const source = readFileSync(file, "utf8");
          const html = enabled
            ? await renderOrderlySsrHtml(await context(), url, source, { userAgent: request.headers["user-agent"] })
            : source;
          const transformed = await server.transformIndexHtml(request.url ?? "/", html);
          response.statusCode = 200;
          response.setHeader("Content-Type", "text/html");
          response.end(transformed);
        } catch (error) {
          next(error);
        }
      });
    }
  };

  function context() {
    contextPromise ??= createOrderlySsrContext({
      root,
      ...options,
      enabled
    });
    return contextPromise;
  }
}
