import vue from '@vitejs/plugin-vue'
import Components from 'unplugin-vue-components/vite'

import { defineConfig } from 'vite'
import { fileURLToPath, URL } from 'node:url'
import { VantResolver } from 'unplugin-vue-components/resolvers'

// https://vite.dev/config/
export default defineConfig({
  plugins: [
    vue(),
    // vueDevTools(),
    Components({
      resolvers: [VantResolver()], // 自动注册 Vant 组件
    }),
  ],
  resolve: {
    alias: {
      '@': fileURLToPath(new URL('./src', import.meta.url)),
    },
  },
  build: {
    // 生成唯一的文件名，避免缓存问题
    rollupOptions: {
      output: {
        // 为 JS 文件添加时间戳
        entryFileNames: `js/[name]-[hash]-${Date.now()}.js`,
        chunkFileNames: `js/[name]-[hash]-${Date.now()}.js`,
        assetFileNames: (assetInfo) => {
          const info = assetInfo.name.split('.')
          const ext = info[info.length - 1]
          if (/\.(css)$/.test(assetInfo.name)) {
            return `css/[name]-[hash]-${Date.now()}.[ext]`
          }
          return `assets/[name]-[hash]-${Date.now()}.[ext]`
        },
      },
    },
  },
  server: {
    host: '0.0.0.0', // 允许外部访问
    port: 5173, // 指定端口
    strictPort: true, // 端口被占用时不会自动选择下一个可用端口
    open: false, // 不自动打开浏览器
    cors: true, // 启用CORS
    // 代理配置（如果需要）
    proxy: {
      // OSS 代理配置
      '/oss': {
        target: 'https://tkm-likei.oss-ap-southeast-1.aliyuncs.com',
        changeOrigin: true,
        secure: true,
        rewrite: (path) => path.replace(/^\/oss/, ''),
        configure: (proxy, options) => {
          proxy.on('proxyRes', (proxyRes, req, res) => {
            // 移除缓存相关的响应头，防止浏览器使用HTTP缓存
            delete proxyRes.headers['etag']
            delete proxyRes.headers['last-modified']
            delete proxyRes.headers['cache-control']
            delete proxyRes.headers['expires']
          })
        },
      },
      // '/api': {
      //   target: 'http://localhost:3000',
      //   changeOrigin: true,
      //   rewrite: (path) => path.replace(/^\/api/, '')
      // }
    },
  },
  preview: {
    host: '0.0.0.0', // 预览模式也允许外部访问
    port: 4173,
    strictPort: true,
    open: false,
  },
})
