import { defineConfig } from 'vite';
import vue from '@vitejs/plugin-vue';
import { resolve } from 'path';
import { resolveDevApiTarget } from '../../scripts/resolve-dev-api-target.mjs';

const devApiTarget = resolveDevApiTarget();

export default defineConfig({
  plugins: [vue()],
  build: {
    rollupOptions: {
      output: {
        manualChunks(id) {
          if (!id.includes('node_modules')) {
            if (id.includes('/src/i18n/zh-CN')) return 'i18n-zh-CN';
            if (id.includes('/src/i18n/en-US')) return 'i18n-en-US';
            if (id.includes('/src/i18n/ms-MY')) return 'i18n-ms-MY';
            return undefined;
          }
          if (id.includes('vue') || id.includes('pinia') || id.includes('vue-router')) {
            return 'vue-vendor';
          }
          if (id.includes('vue-i18n')) return 'i18n-vendor';
          if (id.includes('axios')) return 'axios';
          return undefined;
        },
      },
    },
    chunkSizeWarningLimit: 600,
  },
  resolve: {
    // 避免删除 src 内过期 .js 后仍优先请求 index.js 导致 404
    extensions: ['.ts', '.tsx', '.mjs', '.js', '.mts', '.jsx', '.json', '.vue'],
    alias: {
      // shared 的 dist 为 CommonJS，Vite 无法按命名导出加载；直连源码
      '@thebet365/shared': resolve(__dirname, '../../packages/shared/src/index.ts'),
    },
  },
  publicDir: resolve(__dirname, '../../packages/shared/public'),
  server: {
    host: true,
    port: 5173,
    proxy: {
      '/api': { target: devApiTarget, changeOrigin: true },
      '/uploads': { target: devApiTarget, changeOrigin: true },
    },
  },
});
