import { fileURLToPath, URL } from 'node:url'

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import vueJsx from '@vitejs/plugin-vue-jsx'
import { SetTemplateGroup } from './Configs.js'

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [
    vue({
      template: {
        compilerOptions: {
          comments: false
        }
      }
    }),
    vueJsx()
  ],
  resolve: {
    alias: {
      '@': fileURLToPath(new URL('./src', import.meta.url))
    }
  },
  esbuild: {
    drop: process.env.NODE_ENV === 'production' ? ['console', 'debugger'] : []
  },
  build: {
    rollupOptions: {
      output: {
        manualChunks(id) {
          if (id.includes('/src/')) {
            const group = SetTemplateGroup(id)
            if (group) return `grp_${group}` // group files
          }

          // jquery files
          if (id.includes('node_modules/jquery')) return 'ven_jquery'
          if (id.includes('node_modules/summernote')) return 'ven_summer'
          if (id.includes('node_modules/pdfmake')) return 'ven_pdfmake'
          if (id.includes('node_modules/html-to-pdfmake')) return 'ven_pdfmake'
          if (id.includes('node_modules/vue3-pdfmake')) return 'ven_pdfmake'

          // other node_modules files
          if (id.includes('node_modules')) return 'vendor'
        },
        assetFileNames: (assetInfo) => {
          const name = assetInfo.names?.[0] || assetInfo.name || ''

          if (name.endsWith('.css')) {
            return 'static/css/[name]-[hash][extname]'
          }
          if (/\.(png|jpe?g|svg|gif|webp|ico)$/i.test(name)) {
            return 'static/images/[name]-[hash][extname]'
          }
          if (/\.(ttf|woff2?|eot|otf)$/i.test(name)) {
            return 'static/fonts/[name]-[hash][extname]'
          }
          return 'static/[name]-[hash][extname]'
        },
        chunkFileNames: (chunkInfo) => {
          if (chunkInfo.name?.startsWith('grp_')) return 'static/js/[name]-[hash].js'
          return 'static/js/[name]-[hash].js'
        },
        entryFileNames: 'static/js/[name]-[hash].js'
      }
    }
  }
})
