import { readFileSync } from "node:fs";
import { resolve } from "node:path";
import { defineConfig } from "vitest/config";
import react from "@vitejs/plugin-react";
import type { Connect, Plugin } from "vite";

const mockPresentationPaths: Record<string, string> = {
  "rethinking-econ-ep1": resolve(
    process.cwd(),
    "public/lectures/rethinking-econ-ep1.json"
  )
};

function presentationApiPlugin(): Plugin {
  const handleRequest: Connect.NextHandleFunction = (req, res, next) => {
    if (req.method !== "GET" || !req.url) {
      next();
      return;
    }

    const match = req.url.match(/^\/api\/presentations\/([^/?#]+)/);
    if (!match) {
      next();
      return;
    }

    const presentationId = decodeURIComponent(match[1]);
    const mockPath = mockPresentationPaths[presentationId];

    res.setHeader("Content-Type", "application/json");
    res.setHeader("Cache-Control", "no-store");

    if (!mockPath) {
      res.statusCode = 404;
      res.end(
        JSON.stringify({
          error: "Presentation not found",
          presentationId
        })
      );
      return;
    }

    res.statusCode = 200;
    res.end(readFileSync(mockPath, "utf8"));
  };

  return {
    name: "mock-presentation-api",
    configureServer(server) {
      server.middlewares.use(handleRequest);
    },
    configurePreviewServer(server) {
      server.middlewares.use(handleRequest);
    }
  };
}

export default defineConfig({
  resolve: {
    alias: {
      "@gnommo/slide-contracts": resolve(
        process.cwd(),
        "packages/slide-contracts/src/index.ts"
      )
    }
  },
  plugins: [react(), presentationApiPlugin()],
  test: {
    environment: "jsdom",
    setupFiles: "./src/test/setup.ts",
    globals: true,
    css: true
  }
});
