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

// Split rarely-changing vendor code out of the app chunk so repeat visits and
// post-deploy cache hits don't re-download React, the router, and the icon set.
const manualChunks = (id) => {
  if (!id.includes('node_modules')) return undefined
  if (id.includes('lucide-react')) return 'icons'
  if (id.includes('react-router')) return 'router'
  if (/node_modules\/(react|react-dom|scheduler)\//.test(id)) return 'react-vendor'
  return undefined
}

export default defineConfig(({ isSsrBuild }) => ({
  plugins: [react()],
  resolve: {
    alias: {
      '@': path.resolve(__dirname, './src'),
    },
  },
  server: {
    port: 5173,
    proxy: {
      '/api': {
        target: 'http://localhost:3001',
        changeOrigin: true,
      },
    },
  },
  build: {
    outDir: 'dist',
    sourcemap: process.env.NODE_ENV !== 'production',
    // The SSR bundle externalises its dependencies, so chunking does not apply.
    rollupOptions: isSsrBuild ? {} : { output: { manualChunks } },
  },
}))
