import path from 'node:path'
import react from '@vitejs/plugin-react'
import { defineConfig } from 'vite'
import obfuscatorPlugin from 'vite-plugin-javascript-obfuscator'

const vendorChunks: Record<string, string[]> = {
  'vendor-react': ['react', 'react-dom', 'react-router'],
  'vendor-tdesign': ['tdesign-react', 'tdesign-icons-react'],
  'vendor-recharts': ['recharts'],
}

// https://vite.dev/config/
export default defineConfig({
  plugins: [
    react(),
    obfuscatorPlugin({
      apply: 'build',
      include: ['src/**/*.ts', 'src/**/*.tsx', 'src/**/*.js', 'src/**/*.jsx'],
      exclude: [/node_modules/],
      options: {
        compact: true,
        simplify: true,
        identifierNamesGenerator: 'mangled-shuffled',
        stringArray: true,
        stringArrayCallsTransform: true,
        stringArrayCallsTransformThreshold: 0.5,
        stringArrayEncoding: ['base64'],
        stringArrayIndexShift: true,
        stringArrayRotate: true,
        stringArrayShuffle: true,
        stringArrayWrappersCount: 2,
        stringArrayWrappersChainedCalls: true,
        stringArrayThreshold: 0.75,
        splitStrings: true,
        splitStringsChunkLength: 10,
        numbersToExpressions: true,
        transformObjectKeys: true,
        unicodeEscapeSequence: true,
        debugProtection: true,
        debugProtectionInterval: 2000,
        disableConsoleOutput: true,
        ignoreImports: true,
        controlFlowFlattening: false,
        deadCodeInjection: false,
        selfDefending: false,
        log: false,
      },
    }),
  ],
  resolve: {
    alias: {
      '@': path.resolve(__dirname, './src'),
    },
  },
  server: {
    proxy: {
      '/api': {
        target: `http://localhost:${process.env.NEX_BACKEND_PORT || '9826'}`,
        changeOrigin: true,
      },
    },
  },
  build: {
    chunkSizeWarningLimit: 700,
    sourcemap: false,
    rollupOptions: {
      output: {
        manualChunks(id) {
          for (const [chunkName, modules] of Object.entries(vendorChunks)) {
            for (const mod of modules) {
              if (id.includes(`/node_modules/${mod}/`)) {
                return chunkName
              }
            }
          }
        },
      },
    },
  },
})
