import fs from 'fs'
import path from 'path'
import { fileURLToPath } from 'url'
import vue from '@vitejs/plugin-vue2'
import serveStatic from 'serve-static'

export default {
  plugins: [vue(), customPlugin()],
  resolve: {
    alias: {
      '@': '/src/',
    },
  },
}

function customPlugin() {
  const __dirname = path.dirname(fileURLToPath(import.meta.url))
  const watchDirs = ['packages', 'index.html'].map((item) =>
    path.resolve(__dirname, item).replace(/\\/g, '/')
  )

  return {
    name: 'start-api-serve',
    // 监听 packages 目录的变化
    handleHotUpdate({ file, server }) {
      const shouldReload = watchDirs.some((dir) => file.startsWith(dir))
      if (shouldReload) {
        server.ws.send({
          type: 'full-reload',
          path: '*',
        })
      }
    },
    configureServer(server) {
      const app = server.middlewares

      app.use(serveStatic('dist'))

      app.use('/local-api/plugin-list', (req, res) => {
        let items = getPackageList()

        items = items.map((item) => {
          return {
            ...item,
            aliasName: item.pkgJson.aliasName,
            usePath: `/${item.dirName}/`,
          }
        })
        res.end(httpSuccess({ items }))
      })
    },
  }
}

function getPackageList() {
  const packagesPath = path.resolve(__dirname, './packages')
  let packageList = fs
    .readdirSync(packagesPath)
    .filter((item) => {
      const jsonPath = path.resolve(packagesPath, item, 'bundle.json')
      return fs.existsSync(jsonPath)
    })
    .map((item) => {
      const jsonPath = path.resolve(packagesPath, item, 'bundle.json')
      delete require.cache[require.resolve(jsonPath)]
      const json = require(jsonPath)
      return {
        name: json.name,
        pkgJson: json,
        dirName: item,
      }
    })
  return packageList
}

function httpSuccess(data, message = '操作成功', code = 200) {
  return JSON.stringify({
    code,
    message,
    data,
  })
}
