import { defineConfig } from 'vite' 
import react from '@vitejs/plugin-react' 
import fs from 'fs';

// https://vite.dev/config/
export default defineConfig({
  plugins: [
    react(),
    {
      name: "data-api",
      configureServer(server) {
        server.middlewares.use("/frontend-api/data", (req, res, next) => {
          if (req.method === "POST") {
            let body = "";
            req.on("data", (chunk) => { body += chunk; });
            req.on("end", () => {
              fs.writeFile("public/data.json", body, (err) => {
                if (err) { res.statusCode = 500; res.end(err.message); }
                else { res.statusCode = 200; res.end(JSON.stringify({ ok: true })); }
              });
            });
            return;
          }
          if (req.method === "GET") {
            fs.readFile("public/data.json", "utf-8", (err, data) => {
              if (err) { res.statusCode = 500; res.end(err.message); }
              else { res.statusCode = 200; res.setHeader("Content-Type", "application/json"); res.end(data); }
            });
            return;
          }
          next();
        });
      },
    },
  ],
  server: {
		host: true,
	},
})
