import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import path from 'path'
import fs from 'fs'
import { fileURLToPath } from 'url'

const __dirname = path.dirname(fileURLToPath(import.meta.url))
const promotionRoot = path.resolve(__dirname, 'promotion')

function mimeFor(filePath) {
  const ext = path.extname(filePath).toLowerCase()
  const map = {
    '.mov': 'video/quicktime',
    '.mp4': 'video/mp4',
    '.webm': 'video/webm',
    '.jpg': 'image/jpeg',
    '.jpeg': 'image/jpeg',
    '.png': 'image/png',
    '.gif': 'image/gif',
    '.pdf': 'application/pdf',
    '.pptx': 'application/vnd.openxmlformats-officedocument.presentationml.presentation'
  }
  return map[ext] || 'application/octet-stream'
}

/** 开发时映射 /promotion → web/promotion（含「视频发布」等大文件）。生产环境请部署同路径或 Nginx alias。 */
function promotionDevStatic() {
  return {
    name: 'promotion-dev-static',
    configureServer(server) {
      server.middlewares.use((req, res, next) => {
        if (req.method !== 'GET' && req.method !== 'HEAD') return next()
        const raw = req.url.split('?')[0] || ''
        if (!raw.startsWith('/promotion/') && raw !== '/promotion') return next()
        const rel = raw === '/promotion' ? '' : raw.slice('/promotion/'.length)
        let decoded = rel
        try {
          decoded = decodeURIComponent(rel)
        } catch {
          decoded = rel
        }
        const filePath = path.normalize(path.join(promotionRoot, decoded))
        if (!filePath.startsWith(promotionRoot)) {
          res.statusCode = 403
          res.end('Forbidden')
          return
        }
        fs.stat(filePath, (err, st) => {
          if (err || !st.isFile()) return next()
          res.statusCode = 200
          res.setHeader('Content-Type', mimeFor(filePath))
          if (req.method === 'HEAD') {
            res.end()
            return
          }
          fs.createReadStream(filePath).pipe(res)
        })
      })
    }
  }
}

export default defineConfig({
  appType: 'spa',
  plugins: [vue(), promotionDevStatic()],
  server: {
    port: 3001,
    host: true,
    // 开发时 /api 也走域名（与 .env.development 中 VITE_API_BASE 一致）
    proxy: {
      '/api': {
        target: 'https://yuheng.yuxindazhineng.com',
        changeOrigin: true,
        secure: true,
        ws: true
      }
    }
  }
})
