import react from '@vitejs/plugin-react';
// import { visualizer } from 'rollup-plugin-visualizer';
import { CommonServerOptions, defineConfig, loadEnv, ProxyOptions } from 'vite';
import viteTsconfigPaths from 'vite-tsconfig-paths';

const DEFAULT_PORT = 9999;

function configPort(env: Record<string, string>): CommonServerOptions['port'] {
  const parsedPort = parseInt(env['VITE_PORT']);
  return Number.isNaN(parsedPort) ? DEFAULT_PORT : parsedPort;
}

function configProxy(
  env: Record<string, string>,
): CommonServerOptions['proxy'] {
  const proxyOptions: ProxyOptions = {
    target: env['VITE_PROXY'],
    changeOrigin: true,
    secure: false,
    followRedirects: true,
    autoRewrite: true,
  };

  if (env['VITE_PROXY']) {
    return {
      '/api': proxyOptions,
      '/backend-static': proxyOptions,
    };
  }

  return undefined;
}

export default defineConfig(({ mode = 'development' }) => {
  const env = loadEnv(mode, '.', '');

  return {
    plugins: [
      react({
        babel: {
          babelrc: true,
        },
      }),
      viteTsconfigPaths(),
    ],
    server: {
      open: true,
      host: true,
      port: configPort(env),
      proxy: configProxy(env),
    },
    preview: {
      port: configPort(env),
      proxy: configProxy(env),
    },
    define: {
      'process.env': env,
    },
    build: {
      minify: true,
      chunkSizeWarningLimit: 1024, // 1MB
      // Uncomment rollup `visualizer` plugin to generate bundle size analyzer
      // rollupOptions: {
      //   plugins: [visualizer()],
      // },
    },
  };
});
