import path from "path";
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
import { loadEnv } from "vite";

export default defineConfig(({ mode }) => {
  // Load env file based on `mode` in the current directory.
  const env = loadEnv(mode, process.cwd(), "");

  return {
    plugins: [
      react(),
      {
        name: "html-transform",
        transformIndexHtml(html) {
          return html.replace(
            /<title>(.*?)<\/title>/,
            `<title>${
              mode === "development" ? "[DEV] Dashboard" : "Dashboard"
            }</title>`
          );
        },
      },
    ],
    resolve: {
      alias: {
        "@": path.resolve(__dirname, "./src"),
      },
    },
    server: {
      host: "0.0.0.0",
      port: 3000,
      proxy: {
        "/api/klaviyo": {
          target: "https://dashboard.kent.pw",
          changeOrigin: true,
          secure: true,
          rewrite: (path) => path.replace(/^\/api\/klaviyo/, "/api/klaviyo"),
          configure: (proxy, _options) => {
            proxy.on("error", (err, req, res) => {
              console.error("Klaviyo proxy error:", err);
              res.writeHead(500, {
                "Content-Type": "application/json",
              });
              res.end(
                JSON.stringify({ 
                  error: "Proxy Error", 
                  message: err.message,
                  details: err.stack
                })
              );
            });
            proxy.on("proxyReq", (proxyReq, req, _res) => {
              console.log("Outgoing Klaviyo request:", {
                method: req.method,
                url: req.url,
                path: proxyReq.path,
                headers: proxyReq.getHeaders(),
              });
            });
            proxy.on("proxyRes", (proxyRes, req, _res) => {
              console.log("Klaviyo proxy response:", {
                statusCode: proxyRes.statusCode,
                url: req.url,
                headers: proxyRes.headers,
              });
            });
          },
        },
        "/auth": {
          target: "https://dashboard.kent.pw",
          changeOrigin: true,
          secure: true,
          cookieDomainRewrite: {
            "dashboard.kent.pw": "localhost",
          },
          configure: (proxy, _options) => {
            proxy.on("error", (err, req, res) => {
              console.log("Auth proxy error:", err);
              res.writeHead(500, {
                "Content-Type": "application/json",
              });
              res.end(
                JSON.stringify({ error: "Proxy Error", message: err.message })
              );
            });
            proxy.on("proxyReq", (proxyReq, req, _res) => {
              console.log("Outgoing auth request:", {
                method: req.method,
                url: req.url,
                headers: req.headers,
              });
            });
            proxy.on("proxyRes", (proxyRes, req, _res) => {
              console.log("Auth proxy response:", {
                statusCode: proxyRes.statusCode,
                url: req.url,
                headers: proxyRes.headers,
              });
            });
          },
          onProxyReq: (proxyReq, req, res) => {
            // Log the outgoing request
            console.log("Proxy request:", {
              method: req.method,
              path: req.path,
              headers: req.headers,
            });
          },
          onProxyRes: (proxyRes, req, res) => {
            // Log the incoming response
            console.log("Proxy response:", {
              status: proxyRes.statusCode,
              headers: proxyRes.headers,
            });
          },
        },
        "/api": {
          target: "https://dashboard.kent.pw",
          changeOrigin: true,
          secure: true,
          rewrite: (path) => path.replace(/^\/api/, "/api"),
          configure: (proxy, _options) => {
            proxy.on("error", (err, req, res) => {
              console.log("API proxy error:", err);
              res.writeHead(500, {
                "Content-Type": "application/json",
              });
              res.end(
                JSON.stringify({ error: "Proxy Error", message: err.message })
              );
            });
          },
        },
        "/health": {
          target: "https://dashboard.kent.pw",
          changeOrigin: true,
          secure: true,
          configure: (proxy, _options) => {
            proxy.on("error", (err, req, res) => {
              console.log("Health proxy error:", err);
              res.writeHead(500, {
                "Content-Type": "application/json",
              });
              res.end(
                JSON.stringify({ error: "Proxy Error", message: err.message })
              );
            });
          },
        },
        "/api/aircall": {
          target: "https://dashboard.kent.pw",
          changeOrigin: true,
          secure: true,
          rewrite: (path) => path.replace(/^\/api\/aircall/, "/api/aircall"),
          configure: (proxy, _options) => {
            proxy.on("error", (err, req, res) => {
              console.log("Aircall proxy error:", err);
              res.writeHead(500, {
                "Content-Type": "application/json",
              });
              res.end(
                JSON.stringify({ error: "Proxy Error", message: err.message })
              );
            });
          },
        }
      },
    },
    build: {
      outDir: "build",
      sourcemap: true,
      rollupOptions: {
        output: {
          manualChunks: {
            vendor: ["react", "react-dom", "react-router-dom"],
          },
        },
      },
    },
    define: {
      "process.env": {
        ...env,
        NODE_ENV: JSON.stringify(mode),
      },
    },
  };
});
