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

import { defineConfig, loadEnv } from 'vite'
import Components from '@uni-helper/vite-plugin-uni-components'
import { WotResolver } from '@uni-helper/vite-plugin-uni-components/resolvers'
import { ZPagingResolver } from '@uni-helper/vite-plugin-uni-components/resolvers'
import UniPages from '@uni-helper/vite-plugin-uni-pages'
import UniLayouts from '@uni-helper/vite-plugin-uni-layouts'
import UniManifest from '@uni-helper/vite-plugin-uni-manifest'
import UniPlatform from '@uni-helper/vite-plugin-uni-platform'
import UniRoot from '@uni-ku/root'
import ComponentPlaceholder from '@binbinji/vite-plugin-component-placeholder'
import Uni from '@uni-helper/plugin-uni'
import UnoCSS from 'unocss/vite'

export default defineConfig(({ mode }) => {
  // 加载环境变量（.env / .env.development / .env.production）
  const env = loadEnv(mode, process.cwd(), '')
  const apiUrl = env.VITE_API_URL || ''
  const apiPrefix = env.VITE_API_PREFIX || '/api'

  return {
  resolve: {
    alias: {
      '@': fileURLToPath(new URL('./src', import.meta.url))
    }
  },
  // 开发服务器地址（H5 开发时可将 VITE_API_URL 设为空，使请求走下方 proxy）
  server: {
    host: '0.0.0.0',
    port: 5173,
    open: false,
    proxy: {
      [apiPrefix]: {
        // target: 'http://127.0.0.1:8888', // 本地接口地址
        target: 'https://www.quannengcha.com', // 线上接口地址
        changeOrigin: true,
        rewrite: (path) => path,
      },
    },
  },
  // 注入 API 地址，供 useApiFetch 等使用（未设置时用 .env 中的 VITE_*）
  define: {
    'import.meta.env.VITE_API_URL': JSON.stringify(apiUrl),
    'import.meta.env.VITE_API_PREFIX': JSON.stringify(apiPrefix),
  },
  plugins: [
    // https://uni-helper.js.org/vite-plugin-uni-components
    Components({
      dts: true,
      resolvers: [ZPagingResolver(), WotResolver()]
    }),
    // https://uni-helper.js.org/vite-plugin-uni-pages
    UniPages(),
    // https://uni-helper.js.org/vite-plugin-uni-layouts
    UniLayouts(),
    // https://uni-helper.js.org/vite-plugin-uni-manifest
    UniManifest(),
    // https://uni-helper.js.org/vite-plugin-uni-platform
    UniPlatform(),
    // https://github.com/uni-ku/root
    UniRoot(),
    // https://github.com/chouchouji/vite-plugin-component-placeholder
    ComponentPlaceholder(),
    // https://uni-helper.js.org/plugin-uni
    Uni(),
    UnoCSS(),
  ],
  build: {
    target: 'es6',
    cssTarget: 'chrome61',
  },
  esbuild: {
    // 只在生产环境移除 console 和 debugger，开发环境保留以便调试
    drop: mode === 'production' ? ['console', 'debugger'] : [],
  },
  optimizeDeps: {
    exclude: ['vue-demi']
  },
  }
})


