import { defineConfig, loadEnv } from 'vite'
import { resolve } from 'node:path'
import { wrapperEnv } from './build'
import { setupPlugins } from './build/plugins'

/** 当前执行node命令时文件夹的地址（工作目录） */
const root: string = process.cwd()

/** 路径查找 */
const pathResolve = (dir: string): string => {
  return resolve(__dirname, '.', dir)
}

export default defineConfig(({ command, mode }) => {
  const isBuild = command === 'build'
  const envConf = wrapperEnv(loadEnv(mode, root))

  return {
    base: envConf.VITE_PUBLIC_PATH,
    resolve: {
      alias: {
        '@': pathResolve('src'),
        '@build': pathResolve('build'),
      },
    },
    plugins: setupPlugins(isBuild, envConf, pathResolve),
    server: {
      host: true,
      port: envConf.VITE_PORT,
    },
    css: {
      preprocessorOptions: {
        scss: {
          additionalData: '@use "@/styles/index.scss" as *;',
          api: 'modern-compiler',
        },
      },
    },
    build: {
      rollupOptions: {
        output: {
          manualChunks: {
            dompurify: ['dompurify'],
            'highlight.js': ['highlight.js'],
            marked: ['marked'],
            'github-markdown-css': ['github-markdown-css'],
            'marked-highlight': ['marked-highlight'],
            echarts: ['echarts'],
          },
        },
      },
    },
  }
})
