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

export default defineConfig(({ mode }) => {
  const env = loadEnv(mode, '.', '');
  return {
    server: {
      port: 3000,
      host: '0.0.0.0',
      proxy: {
        '/whmcs-api': {
          target: 'https://my.colocloud.com.bd',
          changeOrigin: true,
          secure: false,
          rewrite: (path) => path.replace(/^\/whmcs-api/, ''),
          headers: {
            'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
            'Accept': 'application/json, text/plain, */*',
            'Accept-Language': 'en-US,en;q=0.9',
            'Referer': 'https://my.colocloud.com.bd/',
            'Origin': 'https://my.colocloud.com.bd'
          },
          configure: (proxy, options) => {
            proxy.on('proxyReq', (proxyReq, req, res) => {
              console.log(`[Proxy] ${req.method} ${req.url} -> ${options.target}`);
            });
            proxy.on('proxyRes', (proxyRes, req, res) => {
              // Remove 'Secure' from Set-Cookie header to allow cookies on localhost (HTTP)
              if (proxyRes.headers['set-cookie']) {
                const cookies = proxyRes.headers['set-cookie'].map(cookie =>
                  cookie.replace(/; secure/gi, '') // Remove '; Secure' flag
                );
                proxyRes.headers['set-cookie'] = cookies;
              }
            });
          }
        },
        '/virtualizor-api': {
          target: 'http://160.187.130.18:4084',
          changeOrigin: true,
          secure: false,
          rewrite: (path) => path.replace(/^\/virtualizor-api/, '')
        },
        '/virtualizor-client-api': {
          target: 'http://160.187.130.18:4082',
          changeOrigin: true,
          secure: false,
          rewrite: (path) => path.replace(/^\/virtualizor-client-api/, '')
        },
        '/vnc-ws-http': {
          target: 'http://160.187.130.18:4081',
          changeOrigin: true,
          secure: false,
          ws: true,
          rewrite: (path) => path.replace(/^\/vnc-ws-http/, '/')
        },
        '/vnc-ws-https': {
          target: 'https://160.187.130.18:4083',
          changeOrigin: true,
          secure: false,
          ws: true,
          rewrite: (path) => path.replace(/^\/vnc-ws-https/, '/')
        },
        '/api': {
          target: 'http://localhost:3001',
          changeOrigin: false,
          secure: false
        }
      }
    },
    plugins: [react()],
    define: {
      'process.env.API_KEY': JSON.stringify(env.GEMINI_API_KEY),
      'process.env.GEMINI_API_KEY': JSON.stringify(env.GEMINI_API_KEY)
    },
    resolve: {
      alias: {
        '@': path.resolve(__dirname, './src'),
      }
    }
  };
});
