import tailwindcss from '@tailwindcss/vite';
import react from '@vitejs/plugin-react';
import path from 'path';
import {defineConfig, loadEnv} from 'vite';

export default defineConfig(({mode}) => {
  // Load all env vars (including non-VITE_ prefixed ones) so the Hasura secret
  // stays server-side in the dev proxy and never reaches the client bundle.
  const env = loadEnv(mode, process.cwd(), '');
  const hasuraSecret = env.HASURA_ADMIN_SECRET || '';

  return {
    plugins: [react(), tailwindcss()],
    resolve: {
      alias: {
        '@': path.resolve(__dirname, '.'),
      },
    },
    server: {
      // HMR is disabled in AI Studio via DISABLE_HMR env var.
      // Do not modify—file watching is disabled to prevent flickering during agent edits.
      hmr: process.env.DISABLE_HMR !== 'true',
      // HMR enabled
      watch: {},
      // Proxy Hasura REST calls so the admin secret is injected server-side
      // (kept out of the browser bundle) and CORS is avoided. The app calls e.g.
      // /hasura/getordersummary?... -> https://api.workolik.com/api/rest/getordersummary?...
      proxy: {
        '/hasura': {
          target: 'https://api.workolik.com',
          changeOrigin: true,
          secure: true,
          rewrite: (p) => p.replace(/^\/hasura/, '/api/rest'),
          configure: (proxy) => {
            proxy.on('proxyReq', (proxyReq) => {
              if (hasuraSecret) {
                proxyReq.setHeader('x-hasura-admin-secret', hasuraSecret);
              }
            });
          },
        },
        // Proxy the Fiesta REST API (fiesta.nearle.app). It is CORS-enabled, but
        // routing through the dev server keeps the network tab consistent with
        // /hasura and sidesteps any preflight surprises. The app calls e.g.
        // /fiesta/live/api/v1/web/orders/getordersummary?... -> https://fiesta.nearle.app/live/api/v1/web/...
        '/fiesta': {
          target: 'https://fiesta.nearle.app',
          changeOrigin: true,
          secure: true,
          rewrite: (p) => p.replace(/^\/fiesta/, ''),
        },
      },
    },
  };
});
