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

import { defineConfig, loadEnv } from 'vite'
import vue from '@vitejs/plugin-vue'
import vueJsx from '@vitejs/plugin-vue-jsx'
import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'
import { createStyleImportPlugin, VxeTableResolve } from 'vite-plugin-style-import'
import Unocss from 'unocss/vite'
import VueDevTools from 'vite-plugin-vue-devtools'
import { sentryVitePlugin } from '@sentry/vite-plugin'
import { lazyImport, VxeResolver } from 'vite-plugin-lazy-import'

export default defineConfig(({ mode }) => {
  const env = loadEnv(mode, process.cwd(), '')

  return {
    base: '/',
    plugins: [
      vue(),
      vueJsx(),
      Unocss(),
      VueDevTools(),
      AutoImport({
        imports: ['vue', 'vue-router', 'pinia', '@vueuse/core'],
        dts: 'src/auto-import.d.ts'
      }),
      Components({
        dirs: ['src/components'],
        extensions: ['vue'],
        dts: 'src/components.d.ts'
      }),
      createSvgIconsPlugin({
        iconDirs: [path.resolve(process.cwd(), 'src/assets/svg')],
        symbolId: 'icon-[dir]-[name]'
      }),
      createStyleImportPlugin({
        resolves: [VxeTableResolve()]
      }),
      mode === 'production' && env.VITE_SENTRY_DSN
        ? sentryVitePlugin({
            org: env.VITE_SENTRY_ORG,
            project: env.VITE_SENTRY_PROJECT,
            authToken: env.VITE_SENTRY_AUTH_TOKEN,
            release: {
              name: env.VITE_SENTRY_RELEASE
            },
            sourcemaps: {
              assets: ['./dist/assets'],
              ignore: ['node_modules']
            }
          })
        : null,
      lazyImport({
        resolvers: [
          VxeResolver({
            libraryName: 'vxe-table'
          }),
          VxeResolver({
            libraryName: 'vxe-pc-ui'
          })
        ]
      })
    ],
    resolve: {
      alias: {
        '@': fileURLToPath(new URL('./src', import.meta.url))
      }
    },
    server: {
      proxy: {
        [env.VITE_BASE_API]: {
          target: env.VITE_BASE_PATH,
          changeOrigin: true
        }
      },
      hmr: {
        overlay: false
      }
    },
    build: {
      sourcemap: !!env.VITE_SENTRY_DSN,
      rollupOptions: {
        output: {
          manualChunks: id => {
            if (id.includes('node_modules')) {
              return 'vender'
            }
          }
        }
      }
    }
  }
})
