import { defineConfig, loadEnv } from 'vite'
import react from '@vitejs/plugin-react'
import { readFileSync } from 'node:fs'

type PackageConfig = {
  appId?: string
  name?: string
  version?: string
}

const packageConfig = JSON.parse(readFileSync(new URL('./package.json', import.meta.url), 'utf-8')) as PackageConfig

// https://vite.dev/config/
export default defineConfig(({ mode }) => {
  const env = loadEnv(mode, process.cwd(), '')
  const baseURL = env.VITE_BASE_URL?.trim()
  const appId = env.VITE_APP_ID?.trim() || packageConfig.appId || packageConfig.name || ''

  return {
    plugins: [react()],
    define: {
      __APP_ID__: JSON.stringify(appId),
      __APP_VERSION__: JSON.stringify(packageConfig.version || ''),
    },
    server: baseURL
      ? {
          proxy: {
            '/api': {
              target: baseURL,
              changeOrigin: true,
            },
          },
        }
      : undefined,
    // alias
    resolve: {
      alias: {
        '@': `${process.cwd()}/src`,
      },
    },
  }
})
