import { URL, fileURLToPath } from 'node:url'
import { type ConfigEnv, defineConfig, loadEnv } from 'vite'
import vue from '@vitejs/plugin-vue'
import vueJsx from '@vitejs/plugin-vue-jsx'

// https://vitejs.dev/config/
export default ({ mode }: ConfigEnv) => {
  const env = loadEnv(mode, './env', 'LEAP')

  const {
    LEAP_PROXY_CONTEXT,
    LEAP_PROXY_HOST,
    LEAP_ROUTER_TYPE,
  } = env

  return defineConfig({
    base: LEAP_ROUTER_TYPE === 'hash' ? './' : '/',
    envDir: './env',
    envPrefix: ['LEAP_', 'APP_'],
    build: {
      manifest: true,
    },
    resolve: {
      alias: {
        '@': fileURLToPath(new URL('./src', import.meta.url)),
        /** Delete below */
        '@ldesign/desktop-next/es': fileURLToPath(new URL('../desktop-next/src', import.meta.url)),
        '@ldesign/desktop-next': fileURLToPath(new URL('../desktop-next/src', import.meta.url)),
        '@ldesign/desktop-profession-next': fileURLToPath(new URL('../desktop-profession-next/src', import.meta.url)),
        '@ldesign/base/lib': fileURLToPath(new URL('../base/src', import.meta.url)),
        '@ldesign/base': fileURLToPath(new URL('../base/src', import.meta.url)),
        '@ldesign/request': fileURLToPath(new URL('../request/src', import.meta.url)),
        '@ldesign/business-next': fileURLToPath(new URL('../business-next/src', import.meta.url)),
        /** End */
      },
    },
    server: {
      host: true,
      port: 8000,
      open: false,
      proxy: {
        [`^/${LEAP_PROXY_CONTEXT}/.*`]: {
          target: LEAP_PROXY_HOST,
          changeOrigin: false,
          rewrite: path => path.replace(/^\//, ''),
        },
      },
    },
    plugins: [
      vue(),
      vueJsx(),
    ],
  })
}
