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 {
    server: {
      hmr: false
    },
    plugins: [
      vue(),
      ...(mode === 'production' ? [
        prerender({
          staticDir: path.join(__dirname, outDir),
          routes: [
            '/', '/en/', '/me/', '/ru/', '/ua/',
            '/en/portfolio', '/me/portfolio', '/ru/portfolio', '/ua/portfolio',
            '/en/about', '/me/about', '/ru/about', '/ua/about',
            '/en/blog', '/me/blog', '/ru/blog', '/ua/blog',
            '/en/contact', '/me/contact', '/ru/contact', '/ua/contact',
            '/en/help', '/me/help', '/ru/help', '/ua/help',
            '/en/guidelines', '/me/guidelines', '/ru/guidelines', '/ua/guidelines',
            '/en/nuances', '/me/nuances', '/ru/nuances', '/ua/nuances',
            '/en/privacy', '/me/privacy', '/ru/privacy', '/ua/privacy',
            '/en/terms', '/me/terms', '/ru/terms', '/ua/terms',
            '/en/careers', '/me/careers', '/ru/careers', '/ua/careers',
            '/en/scanning', '/me/scanning', '/ru/scanning', '/ua/scanning',
          ],
          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",
    },
  };
});
