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

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [react()],
  envPrefix: ['VITE_', 'ROMM_'],
  server: {
    watch: {
      usePolling: true,
    },
    cors: true,
    proxy: {
      '/api': {
        target: 'https://retro.chieflix.com',
        changeOrigin: true,
        secure: false,
        configure: (proxy: any) => {
          proxy.on('proxyReq', (proxyReq: any, req: any) => {
            // New Token Path Strategy: Extract token from URL path to prevent EmulatorJS extension parsing bugs
            // Match format: /api/roms/123/content/token/XYZ/rom.chd
            const tokenMatch = req.url?.match(/\/content\/token\/([^/]+)\/(.*)/);
            if (tokenMatch) {
              const token = tokenMatch[1];
              const restOfPath = tokenMatch[2];
              
              // Inject the token securely
              proxyReq.setHeader('Authorization', `Bearer ${token}`);
              
              // Rewrite the proxy request path to hide the token and the false filename from the RomM backend
              // E.g., /api/roms/123/content/token/TOKEN/game.nds -> /api/roms/123/content
              let newPath = req.url.replace(/\/content\/token\/[^/]+\/.*/, '/content');
              
              // EJS loader often fires HEAD requests to check content-length. RomM FastAPI natively drops HEAD methods on binary routes returning 404s.
              // Mutate HEAD queries safely into GET queries so the backend responds with accurate Header structures.
              if (req.method === 'HEAD') {
                proxyReq.method = 'GET';
              }
              
              proxyReq.path = newPath;
            } else {
              // Fallback for regular query params (Saves/States)
              const url = new URL(req.url || '', `http://${req.headers.host}`);
              const token = url.searchParams.get('access_token');
              if (token) {
                proxyReq.setHeader('Authorization', `Bearer ${token}`);
              }
            }
          });
          proxy.on('proxyRes', (proxyRes: any) => {
            proxyRes.headers['Cross-Origin-Resource-Policy'] = 'cross-origin';
          });
        }
      }
    }
  },
})
