import * as path from 'path';
import { sentryVitePlugin } from '@sentry/vite-plugin';
import legacy from '@vitejs/plugin-legacy';
import react from '@vitejs/plugin-react-swc';
import { defineConfig, loadEnv } from 'vite';
import checker from 'vite-plugin-checker';
import tsconfigPaths from 'vite-tsconfig-paths';
import { nodeResolve } from '@rollup/plugin-node-resolve';
import { createRequire } from 'module';
const require = createRequire(import.meta.url);

/** @type {import('vite').UserConfig} */
export default ({ mode }) => {
  process.env = { ...process.env, ...loadEnv(mode, process.cwd()) };

  const plugins = [
    tsconfigPaths(),
    legacy({
      targets: ['chrome >= 64', 'safari >= 12', 'edge >= 79', 'firefox >= 67'],
      modernPolyfills: ['es.object.from-entries', 'es/global-this', 'web/queue-microtask.js'],
      ignoreBrowserslistConfig: true,
      renderLegacyChunks: false,
    }),
    checker({
      // e.g. use TypeScript check
      typescript: true,
      overlay: false,
      lintCommand: 'eslint "./src/**/*.{ts,tsx}"',
    }),
    react({
      jsxImportSource: '@emotion/react',
      babel: {
        plugins: ['@emotion/babel-plugin'],
      },
    }),
  ];

  if (mode === 'production') {
    plugins.push(
      sentryVitePlugin({
        org: 'media-cc',
        project: 'javascript-react',
        authToken: process.env.SENTRY_AUTH_TOKEN,
        bundleSizeOptimizations: {
          excludeDebugStatements: true,
          // Only relevant if you added `browserTracingIntegration`
          excludePerformanceMonitoring: true,
          // Only relevant if you added `replayIntegration`
          excludeReplayIframe: true,
          excludeReplayShadowDom: true,
          excludeReplayWorker: true,
        },
        disable: false,
      }),
    );
  }
  
  return defineConfig({
    build: {
      outDir: 'build',
      sourcemap: true,
      target: 'es2015',
      rollupOptions: {
        plugins: [
          nodeResolve({
            // Add the node-resolve plugin here
            browser: true, // Resolve for browser environment (set to false for Node.js)
            preferBuiltins: false, // Avoid using Node.js built-ins if you don't want them
          }),
        ],
      },
    },
    esbuild: {
      drop: [],
    },
    plugins: plugins,
    server: {
      host: 'localhost',
      port: 3000,
      proxy: {
        '/auth': {
          target: process.env.VITE_APP_AUTH_PROXY_HOST,
          changeOrigin: true,
          secure: false,
        },
        '/api': {
          target: process.env.VITE_APP_API_PROXY_HOST,
          changeOrigin: true,
          secure: false,
        },
      },
    },
    test: {
      globals: true,
      environment: 'jsdom',
      setupFiles: ['./vitest.setup.ts'],
      alias: {
        '~': path.resolve(__dirname, 'src'),
      },
    },
    resolve: {
      alias: {
        '~': path.resolve(__dirname, 'src'),
        '@use-blocker': path.resolve(__dirname, 'src/shared/lib/hooks/use-blocker.ts'),
      },
    },
    cacheDir: './.vite',
    optimizeDeps: {
      entries: ['./index.html'],
    },
  });
};
