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

import { defineConfig, loadEnv } from 'vite'
import vue from '@vitejs/plugin-vue'
import vueDevTools from 'vite-plugin-vue-devtools'
import Components from 'unplugin-vue-components/vite'
import { AntDesignVueResolver } from 'unplugin-vue-components/resolvers'
import { readFileSync } from 'fs'
import { formatDateTime } from './src/utils'
import buildInfoPlugin from './scripts/build-info-plugin'

// https://vite.dev/config/
export default defineConfig(({ mode }) => {
  // 加载环境变量
  const env = loadEnv(mode, process.cwd(), '')
  // 获取当前环境的API主机
  const apiHost = env.VITE_APP_HOST
  // 添加日志输出
  console.log(`🚀CurrentMode: ${mode}`)
  console.log(`🚀HostAPI: ${apiHost}`)
  console.log(`🚀ProxyAPI: ${apiHost}`)

  const pkg = JSON.parse(readFileSync('./package.json', 'utf-8'))
  return {
    plugins: [
      vue(),
      vueDevTools(),
      buildInfoPlugin(mode),
      Components({
        resolvers: [
          AntDesignVueResolver({
            importStyle: false, // css in js
          }),
        ],
      }),
    ],
    define: {
      __APP_VERSION__: JSON.stringify(pkg.version),
      __BUILD_TIME__: JSON.stringify(formatDateTime(new Date())),
    },
    resolve: {
      alias: {
        '@': fileURLToPath(new URL('./src', import.meta.url)),
      },
    },
    server: {
      proxy: {
        '/portal-service-server': {
          target: apiHost,
          changeOrigin: true,
          secure: false,
          rewrite: (path) => path,
        },
        '/pub': {
          target: apiHost,
          changeOrigin: true,
          secure: false,
          rewrite: (path) => path,
        },
      },
      cors: true,
    },
  }
})
