import type { Plugin } from 'vite'
import fs from 'node:fs'
import path from 'node:path'

export default function pushUpdatePlugin(): Plugin {
  // const virtualId = 'virtual:push-update'
  // const resolveVirtualId = '\0' + virtualId
  return {
    name: 'push-update-plugin',
    apply: 'build',
    // resolveId(id) {
    //   if (id === virtualId) {
    //     return resolveVirtualId
    //   }
    // },
    // load(id) {
    //   if (id === resolveVirtualId) {
    //     let updateInfo = ''
    //     try {
    //       updateInfo = fs.readFileSync(path.resolve(process.cwd(), 'pushUpdate.txt'), 'utf-8')
    //     } catch (error) {
    //       const err = error as NodeJS.ErrnoException
    //       if (err.code !== 'ENOENT') {
    //         throw err
    //       }
    //     }
    //     return `export default ${JSON.stringify(updateInfo)}`
    //   }
    // },
    writeBundle(options) {
      const version = Date.now().toString()
      let updateInfo = ''
      try {
        updateInfo = fs.readFileSync(path.resolve(process.cwd(), 'pushUpdate.txt'), 'utf-8') || ''
      } catch (error) {
        const err = error as NodeJS.ErrnoException
        if (err.code !== 'ENOENT') {
          throw err
        }
      }

      const outDir = options.dir || path.resolve(process.cwd(), 'dist')
      const filePath = path.resolve(outDir, 'version.json')
      fs.writeFileSync(
        filePath,
        JSON.stringify({ version, updateInfo }, null, 2), // 存成 json
        'utf-8',
      )
    },
  }
}
