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

const __dirname = path.dirname(fileURLToPath(import.meta.url))

export default defineConfig({
  plugins: [
    vue(),
    {
      name: 'serve-data-dir',
      configureServer(server) {
        server.middlewares.use('/novel-data', (req, res, next) => {
          // req.url 会像 /dtslz/data/vol01.json
          const filePath = path.resolve(__dirname, '../fiction', req.url.replace(/^\//, '').split('?')[0])
          try {
            const content = fs.readFileSync(filePath, 'utf-8')
            res.setHeader('Content-Type', 'application/json; charset=utf-8')
            res.end(content)
          } catch {
            next()
          }
        })
      }
    }
  ],
  server: {
    port: 5173,
    proxy: {
      '/tiles': {
        target: 'http://192.168.190.41:8080',
        changeOrigin: true,
        rewrite: (path) => path.replace(/^\/tiles/, '')
      },
      '/api': {
        target: 'http://127.0.0.1:8000',
        changeOrigin: true
      }
    }
  },
  build: {
    outDir: resolve(__dirname, '../dist')
  }
})
