/**
 * Self-destruct service worker (kill switch).
 *
 * The old StudySphere PWA registered a service worker that cached the old app
 * and kept serving it to returning users even after the v2 deploy. v2 does NOT
 * use a service worker, so this file replaces the old one at the same URL.
 *
 * When a browser re-checks the SW script (it does on navigation), it receives
 * this version, which clears every cache, unregisters itself, and reloads all
 * open tabs — so users get the fresh v2 with no manual cache clearing.
 */
self.addEventListener('install', () => {
  self.skipWaiting()
})

self.addEventListener('activate', (event) => {
  event.waitUntil(
    (async () => {
      try {
        const keys = await caches.keys()
        await Promise.all(keys.map((k) => caches.delete(k)))
      } catch (e) { /* ignore */ }
      try {
        await self.registration.unregister()
      } catch (e) { /* ignore */ }
      const clients = await self.clients.matchAll({ type: 'window' })
      clients.forEach((c) => {
        try { c.navigate(c.url) } catch (e) { /* ignore */ }
      })
    })(),
  )
})

// Never serve from cache — always hit the network.
self.addEventListener('fetch', () => {})
