import { fileURLToPath, URL } from 'node:url'
import { writeFileSync, readFileSync, existsSync } from 'node:fs'
import { resolve } from 'node:path'

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import vueDevTools from 'vite-plugin-vue-devtools'

// https://vite.dev/config/
export default defineConfig({
  plugins: [
    vue(),
    vueDevTools(),
    {
      name: 'update-sw-version',
      apply: 'build',
      closeBundle() {
        const swPath = resolve(fileURLToPath(new URL('.', import.meta.url)), 'dist/service-worker.js')
        if (existsSync(swPath)) {
          let content = readFileSync(swPath, 'utf8')
          const timestamp = new Date().toISOString()
          content = content.replace(/const VERSION = '.*';/, `const VERSION = '${timestamp}';`)
          writeFileSync(swPath, content)
          console.log(`[SW Update] Version updated to ${timestamp}`)
        }
      }
    }
  ],
  resolve: {
    alias: {
      '@': fileURLToPath(new URL('./src', import.meta.url))
    },
  },
  build: {
    // 确保 Service Worker 和 manifest 被正确复制
    rollupOptions: {
      input: {
        main: fileURLToPath(new URL('./index.html', import.meta.url))
      }
    }
  },
  server: {
    headers: {
      // 允许 Service Worker 在开发环境中工作
      'Service-Worker-Allowed': '/'
    }
  }
})
