import path from "path"
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import { loadEnv } from "vite"
import fs from 'fs-extra'

// https://vitejs.dev/config/
export default defineConfig(({ mode }) => {
  const env = loadEnv(mode, process.cwd(), "")
  const isDev = mode === 'development'

  return {
    plugins: [
      react(),
      {
        name: 'copy-build',
        closeBundle: async () => {
          if (!isDev) {
            const sourcePath = path.resolve(__dirname, 'build');
            const targetPath = path.resolve(__dirname, '../inventory-server/frontend/build');
            
            try {
              await fs.ensureDir(path.dirname(targetPath));
              await fs.remove(targetPath);
              await fs.copy(sourcePath, targetPath);
              console.log('Build files copied successfully to server directory!');
            } catch (error) {
              console.error('Error copying build files:', error);
              process.exit(1);
            }
          }
        }
      }
    ],
    define: {
      'process.env.NODE_ENV': JSON.stringify(mode)
    },
    resolve: {
      alias: {
        "@": path.resolve(__dirname, "./src"),
      },
    },
    server: {
      host: "0.0.0.0",
      port: 5175,
      proxy: {
        "/api/aircall": {
          target: "https://dashboard.kent.pw",
          changeOrigin: true,
          secure: false,
          rewrite: (path) => path,
        },
        "/api/klaviyo": {
          target: "https://dashboard.kent.pw",
          changeOrigin: true,
          secure: false,
          rewrite: (path) => path,
        },
        "/api/meta": {
          target: "https://dashboard.kent.pw",
          changeOrigin: true,
          secure: false,
          rewrite: (path) => path,
        },
        "/api/gorgias": {
          target: "https://dashboard.kent.pw",
          changeOrigin: true,
          secure: false,
          rewrite: (path) => path,
        },
        "/api/dashboard-analytics": {
          target: "https://dashboard.kent.pw",
          changeOrigin: true,
          secure: false,
          rewrite: (path) => path.replace("/api/dashboard-analytics", "/api/analytics"),
        },
        "/api/typeform": {
          target: "https://dashboard.kent.pw",
          changeOrigin: true,
          secure: false,
          rewrite: (path) => path,
        },
        "/api/acot": {
          target: "https://dashboard.kent.pw",
          changeOrigin: true,
          secure: false,
          rewrite: (path) => path,
        },
        "/api/clarity": {
          target: "https://dashboard.kent.pw",
          changeOrigin: true,
          secure: false,
          rewrite: (path) => path,
        },
        "/api": {
          target: "https://inventory.kent.pw",
          changeOrigin: true,
          secure: false,
          ws: true,
          xfwd: true,
          cookieDomainRewrite: "",
          withCredentials: 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 })
              )
            })
            proxy.on("proxyReq", (proxyReq, req, _res) => {
              console.log("Outgoing request to API:", {
                method: req.method,
                url: req.url,
                headers: proxyReq.getHeaders(),
              })
            })
            proxy.on("proxyRes", (proxyRes, req, _res) => {
              console.log("API Proxy response:", {
                statusCode: proxyRes.statusCode,
                url: req.url,
                headers: proxyRes.headers,
              })
            })
          },
        },
        "/dashboard-auth": {
          target: "https://dashboard.kent.pw",
          changeOrigin: true,
          secure: false,
          ws: true,
          rewrite: (path) => path.replace("/dashboard-auth", "/auth"),
        },
        "/auth-inv": {
          target: "https://inventory.kent.pw",
          changeOrigin: true,
          secure: false,
          ws: true,
          xfwd: true,
          cookieDomainRewrite: {
            "inventory.kent.pw": "localhost"
          },
          withCredentials: true,
          onProxyReq: (proxyReq, req) => {
            // Add origin header to match CORS policy
            proxyReq.setHeader('Origin', 'http://localhost:5175');
          },
          rewrite: (path) => path.replace(/^\/auth-inv/, "/auth-inv"),
          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 request to Auth:", {
                method: req.method,
                url: req.url,
                headers: proxyReq.getHeaders(),
              })
            })
            proxy.on("proxyRes", (proxyRes, req, _res) => {
              console.log("Auth Proxy response:", {
                statusCode: proxyRes.statusCode,
                url: req.url,
                headers: proxyRes.headers,
              })
            })
          },
        },
        "/chat-api": {
          target: "https://inventory.kent.pw",
          changeOrigin: true,
          secure: false,
          ws: true,
          xfwd: true,
          cookieDomainRewrite: "",
          withCredentials: true,
          rewrite: (path) => path,
          configure: (proxy, _options) => {
            proxy.on("error", (err, req, res) => {
              console.log("Chat API 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 request to Chat API:", {
                method: req.method,
                url: req.url,
                headers: proxyReq.getHeaders(),
              })
            })
            proxy.on("proxyRes", (proxyRes, req, _res) => {
              console.log("Chat API Proxy response:", {
                statusCode: proxyRes.statusCode,
                url: req.url,
                headers: proxyRes.headers,
              })
            })
          },
        },
        "/uploads": {
          target: "https://inventory.kent.pw",
          changeOrigin: true,
          secure: false,
          rewrite: (path) => path,
        },
      },
    },
    build: {
      outDir: "build",
      sourcemap: true,
      chunkSizeWarningLimit: 1000,
      rollupOptions: {
        output: {
          manualChunks: {
            // Simple static chunking approach - safer than function-based chunking
            'react-vendor': ['react', 'react-dom', 'react-router-dom'],
            'ui-vendor': ['@radix-ui/react-dialog', '@radix-ui/react-dropdown-menu', 'lucide-react'],
            'query-vendor': ['@tanstack/react-query'],
          },
        },
      },
    },
  }
})
