import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import { VitePWA } from 'vite-plugin-pwa'
import { readFileSync, copyFileSync, existsSync } from 'fs'

const pkg = JSON.parse(readFileSync('./package.json', 'utf-8'))

function copySqliteWasm() {
  return {
    name: 'copy-sqlite-wasm',
    buildStart() {
      const src = 'node_modules/@sqlite.org/sqlite-wasm/dist/sqlite3.wasm'
      const dest = 'public/sqlite3.wasm'
      if (existsSync(src)) copyFileSync(src, dest)
    },
  }
}

export default defineConfig({
  base: './',
  plugins: [
    vue(),
    copySqliteWasm(),
    VitePWA({
      registerType: 'prompt',
      manifest: false,
      workbox: {
        globPatterns: ['**/*.{js,css,html,ico,png,svg,wasm,woff,woff2}'],
        maximumFileSizeToCacheInBytes: 10 * 1024 * 1024,
        runtimeCaching: [
          {
            urlPattern: ({ request }) => request.destination === 'image',
            handler: 'CacheFirst',
            options: {
              cacheName: 'exercise-images',
              expiration: {
                maxEntries: 300,
                maxAgeSeconds: 30 * 24 * 60 * 60,
              },
              cacheableResponse: {
                statuses: [0, 200],
              },
            },
          },
        ],
      },
      devOptions: {
        enabled: true,
        type: 'module',
      },
    }),
  ],
  define: {
    __APP_VERSION__: JSON.stringify(pkg.version),
    __APP_NAME__: JSON.stringify(pkg.name),
  },
  server: {
    headers: {
      'Cross-Origin-Opener-Policy': 'same-origin',
      // 'credentialless' is a relaxed alternative to 'require-corp' that
      // allows cross-origin images without CORP headers — useful in dev.
      // Production deployments should use 'require-corp' (see README).
      'Cross-Origin-Embedder-Policy': 'credentialless',
    },
  },
  optimizeDeps: {
    exclude: ['@sqlite.org/sqlite-wasm'],
  },
})
