import { defineConfig } from "vite";
import vue from "@vitejs/plugin-vue";
import path from "path";
import { createRequire } from 'module';
const require = createRequire(import.meta.url);
const prerender = require('vite-plugin-prerender');

export default defineConfig(({ mode }) => {
  console.log(`🔨 Vite build mode: ${mode}`);
  const outDir = process.env.VITE_OUT_DIR || 'dist';
  return {
    plugins: [
      vue(),
      prerender({
        staticDir: path.join(__dirname, outDir),
        routes: ['/', '/en/', '/me/', '/ru/', '/ua/'],
        renderer: new prerender.PuppeteerRenderer({
          renderAfterDocumentEvent: 'render-event',
          injectProperty: '__PRERENDER_INJECTED',
          maxTimeout: 30000,
          headless: true,
          args: [
            '--no-sandbox', 
            '--disable-setuid-sandbox',
            '--disable-dev-shm-usage',
            '--disable-gpu',
            '--single-process'
          ],
          consoleHandler: (route: string, message: any) => {
            console.log(`[🔨 Prerender Console - ${route}] ${message.text()}`);
          }
        }),
        postProcess(renderedRoute: any) {
          console.log(`[🔨 Prerender] Finished: ${renderedRoute.route}`);
          return renderedRoute;
        }
      })
  ],
  resolve: {
    alias: {
      "@": path.resolve(__dirname, "./src"),
    },
  },
  build: {
    outDir: outDir, 
    target: 'es2018',
    chunkSizeWarningLimit: 1000,
    cssMinify: true,
    minify: 'esbuild',
    rollupOptions: {
      output: {
        manualChunks: {
          'three-vendor': ['three'],
          'ui-vendor': ['lucide-vue-next', '@vueuse/core'],
        }
      }
    }
  },
  esbuild: {
    legalComments: 'none',
    target: 'es2018',
  },
    test: {
      globals: true,
      environment: "jsdom",
    },
  };
});
