import path from 'node:path'
import type { ConfigEnv } from 'vite'
import { defineConfig, loadEnv } from 'vite'
import vue from '@vitejs/plugin-vue'
import Components from 'unplugin-vue-components/vite'
import { VantResolver } from 'unplugin-vue-components/resolvers'
import AutoImport from 'unplugin-auto-import/vite'
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'

export default defineConfig((mode: ConfigEnv) => {
  // eslint-disable-next-line node/prefer-global/process
  const env = loadEnv(mode.mode, process.cwd())
  return {
    base: '/sdream-h5/',
    build: {
      outDir: 'sdream-h5',
    },
    define: {
      'process.env': {
        VITE_APP_BASE_API: env.VITE_APP_BASE_API,
        VITE_NODE_ENV: env.VITE_NODE_ENV,
        VITE_APP_WECHAT_APP_ID: env.VITE_APP_WECHAT_APP_ID,
        VITE_APP_WECHAT_SUB_APP_ID: env.VITE_APP_WECHAT_SUB_APP_ID,
      },
    },
    plugins: [
      vue(),
      createSvgIconsPlugin({
        // 指定需要缓存的图标文件夹
        iconDirs: [path.resolve(__dirname, './src/assets/svg')],
        // 指定symbolId格式
        symbolId: 'icon-[dir]-[name]',
      }),
      Components({
        extensions: ['vue'],
        dts: 'src/components.d.ts',
        include: [/\.vue$/, /\.vue\?vue/],
        resolvers: [VantResolver()],
      }),
      AutoImport({
        imports: [
          'vue',
          'vue-router',
        ],
        dts: 'src/auto-imports.d.ts',
        dirs: [
          'src/hooks',
        ],
        vueTemplate: true,
      }),
    ],
    resolve: {
      alias: {
        '@': path.resolve(__dirname, 'src'),
      },
    },
    server: {
      host: '0.0.0.0',
      port: 3001,
      open: true,
      proxy: {
        '/api': {
          target: env.VITE_APP_BASE_API,
          secure: false,
          changeOrigin: true,
          rewrite: path => path.replace(/^\/api/, ''),
        },
      },
    },
    css: {
      preprocessorOptions: {
        scss: {
          additionalData: '@import "@/styles/globalVar.scss";',
        },
      },
    },
  }
})
