import { defineConfig, loadEnv } from 'vite'
import vue from '@vitejs/plugin-vue'
import tailwindcss from '@tailwindcss/vite'
import { fileURLToPath, URL } from 'node:url'
import { resolve } from 'node:path'

export default defineConfig(({ mode }) => {
  // Load env from project root (two levels up from resource/frontend)
  const projectRoot = resolve(__dirname, '../..')
  const env = loadEnv(mode, projectRoot, '')

  const apiPort = env.VITE_API_PORT || '5000'
  const clientPort = env.VITE_CLIENT_PORT || '4200'
  const basePath = env[`DKU_CODE_STUDIO_BROWSER_PATH_${clientPort}`] || '/'

  return {
    plugins: [vue(), tailwindcss()],
    resolve: {
      alias: {
        '@': fileURLToPath(new URL('./src', import.meta.url)),
      },
    },
    base: basePath,
    server: {
      host: '127.0.0.1',
      port: parseInt(clientPort),
      proxy: {
        '/api': {
          target: `http://127.0.0.1:${apiPort}`,
          changeOrigin: true,
          secure: false,
        },
      },
    },
    build: {
      outDir: '../dist',
      emptyOutDir: true,
      // Disable code splitting - DSS serves webapps from dynamic base paths
      // that break Vite's chunk loading. Bundle everything into a single file.
      rollupOptions: {
        output: {
          // Disable all code splitting - put everything in one file
          manualChunks: undefined,
          inlineDynamicImports: true,
          entryFileNames: `assets/[name].js`,
          assetFileNames: `assets/[name].[ext]`,
        },
      },
    },
    // Pass env variables to the client
    define: {
      'import.meta.env.VITE_API_PORT': JSON.stringify(apiPort),
      'import.meta.env.VITE_CLIENT_PORT': JSON.stringify(clientPort),
    },
  }
})
