import { defineConfig, loadEnv } from 'vite'
import { readFileSync } from 'node:fs'
import vue from '@vitejs/plugin-vue'
import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'

const versions = readFileSync(new URL('../versions.props', import.meta.url), 'utf8')
const frontendVersion = /<JiaowuFrontendVersion>([^<]+)<\/JiaowuFrontendVersion>/.exec(versions)?.[1]

if (!frontendVersion) {
  throw new Error('versions.props 中缺少 JiaowuFrontendVersion。')
}

// https://vite.dev/config/
export default defineConfig(({ mode }) => {
  const env = loadEnv(mode, process.cwd(), '')
  const isCapacitor = env.VITE_ROUTER_MODE === 'hash'

  return {
    define: {
      __APP_VERSION__: JSON.stringify(frontendVersion),
    },
    plugins: [
      vue(),
      AutoImport({
        resolvers: [ElementPlusResolver()],
        dts: 'src/auto-imports.d.ts',
      }),
      Components({
        resolvers: [ElementPlusResolver({ importStyle: 'css', directives: true })],
        dts: 'src/components.d.ts',
      }),
    ],
    base: isCapacitor ? './' : '/',
    build: {
      outDir: isCapacitor ? 'dist' : '../src/Jiaowu.Api/wwwroot',
      emptyOutDir: true,
    },
    server: {
      port: 5173,
      proxy: {
        '/api': {
          target: 'http://localhost:5255',
          changeOrigin: true,
        },
        '/health': {
          target: 'http://localhost:5255',
          changeOrigin: true,
        },
      },
    },
  }
})
