/// <reference types="vitest" />
import { defineConfig, loadEnv } from 'vite'; // 从 vite 导入 loadEnv
import vue from '@vitejs/plugin-vue';
import { fileURLToPath, URL } from 'node:url';
import vueJsx from '@vitejs/plugin-vue-jsx';
import AutoImport from 'unplugin-auto-import/vite';
import Components from 'unplugin-vue-components/vite';
import { ElementPlusResolver, VantResolver } from 'unplugin-vue-components/resolvers';
import postCssPxToRem from 'postcss-pxtorem';
import legacy from '@vitejs/plugin-legacy';
// shift +  alt 快速定位到对应组件
import { codeInspectorPlugin } from 'code-inspector-plugin';
// 导入 dev tools
import vueDevTools from 'vite-plugin-vue-devtools';

export default defineConfig(({ mode }) => {
  // 接收 mode 参数
  // 正确加载环境变量
  const env = loadEnv(mode, process.cwd());

  // 从 env 对象中获取变量
  const proxyUrl = env.VITE_APP_BASEURL;
  const proxyUrlDelivery = env.VITE_APP_DELIVERY_BASEURL;
  return {
    // 必须 return 配置对象
    server: {
      allowedHosts: ['yiligpt.x.digitalyili.com'],
      host: '0.0.0.0',
      port: 3000,
      proxy: {
        '/backend-api': {
          target: proxyUrl,
          changeOrigin: true,
          pathRewrite: {
            '^/backend-api': '' // 路径重写
          },
          // bypass: (req) => req.headers.accept?.indexOf('html') !== -1, // 跳过 HTML 请求
          cookieDomainRewrite: 'localhost'
        },
        '/request-java': {
          target: `${proxyUrlDelivery}/api`,
          changeOrigin: true,
          pathRewrite: { '^/request-java': '' }
        }
      }
    },
    css: {
      postcss: {
        plugins: [
          postCssPxToRem({
            rootValue: 37.5,
            propList: ['*']
          })
        ]
      },
      preprocessorOptions: {
        scss: { api: 'modern-compiler' }
      }
    },
    build: {
      target: 'es2015',
      minify: 'terser',
      terserOptions: {
        compress: {
          drop_console: true,
          drop_debugger: true
        }
      }
    },
    cacheDir: '.tmp',
    plugins: [
      // vueDevTools(),
      vue({
        template: {
          compilerOptions: {
            // 将 swiper 相关标签注册为自定义元素
            isCustomElement: (tag) => tag.startsWith('swiper-')
          }
        }
      }),
      vueJsx(),
      AutoImport({ resolvers: [VantResolver(), ElementPlusResolver()] }),
      Components({ resolvers: [VantResolver(), ElementPlusResolver()] }),
      legacy({
        targets: ['ie >= 11', 'chrome >= 49', 'safari >= 11.1'],
        additionalLegacyPolyfills: ['regenerator-runtime/runtime']
      }),
      codeInspectorPlugin({
        bundler: 'vite'
      })
      // tailwindcss()
    ],
    resolve: {
      alias: {
        '@': fileURLToPath(new URL('./src', import.meta.url))
      }
    }
  };
});
