import { defineConfig } from 'vite';
import vue from '@vitejs/plugin-vue';
import { resolve } from 'path';
import { visualizer } from 'rollup-plugin-visualizer';

export default defineConfig(({ mode }) => {
  const analyze = process.env.ANALYZE === '1' || mode === 'analyze';

  return {
  plugins: [
    vue(),
    analyze &&
      visualizer({
        filename: 'dist/stats.html',
        gzipSize: true,
        brotliSize: true,
        open: false,
      }),
  ].filter(Boolean),
  resolve: {
    extensions: ['.mjs', '.ts', '.mts', '.tsx', '.vue', '.js', '.jsx', '.json'],
    alias: {
      '@thebet365/shared': resolve(__dirname, '../../packages/shared/src/index.ts'),
    },
    dedupe: ['echarts', 'vue-echarts', 'vue'],
  },
  optimizeDeps: {
    include: ['echarts', 'vue-echarts'],
  },
  build: {
    chunkSizeWarningLimit: 600,
    rollupOptions: {
      output: {
        manualChunks(id) {
          if (!id.includes('node_modules')) {
            if (id.includes('/src/i18n/bundles/')) {
              const m = id.match(/bundles\/(zh-CN|en-US|ms-MY)/);
              if (m) return `i18n-${m[1]}`;
            }
            if (id.includes('/src/i18n/pages/')) return 'i18n-pages';
            if (id.includes('echarts-setup') || id.includes('vue-echarts') || id.includes('node_modules/echarts')) {
              return 'echarts';
            }
            return undefined;
          }
          if (id.includes('element-plus')) return 'element-plus';
          if (id.includes('echarts')) return 'echarts';
          if (id.includes('vue-i18n')) return 'vue-i18n';
          if (id.includes('vue-router')) return 'vue-router';
          if (id.includes('vue/') || id.includes('vue/dist')) return 'vue';
          return undefined;
        },
      },
    },
  },
  publicDir: resolve(__dirname, '../../packages/shared/public'),
  server: {
    port: 5174,
    proxy: {
      '/api': { target: 'http://localhost:3000', changeOrigin: true },
      '/uploads': { target: 'http://localhost:3000', changeOrigin: true },
    },
  },
};
});
