/*
 * Service worker — deliberately small, and deliberately timid.
 *
 * THE RISK THIS IS WRITTEN AGAINST. A service worker is the one thing on a site
 * that can outlive a bad deploy: it sits in front of the network on every
 * request, it survives reloads, and a visitor cannot clear it. Get it wrong and
 * users are pinned to a stale build with no way back that you can push. This
 * site deploys on every merge to main, several times on a test day, so that is
 * not a hypothetical.
 *
 * So the rules here are the conservative ones:
 *
 *   • The HTML shell is NETWORK-FIRST. index.html already carries
 *     Cache-Control: no-cache for exactly this reason; a cache-first worker
 *     would quietly undo that. The cached copy is a fallback for being offline,
 *     never a preference.
 *   • Hashed assets are cache-first, because /assets/index-CuNToqC1.js is
 *     immutable by construction — a new build produces a new name. The deploy
 *     adds assets and never prunes them (see deploy.yml), so an old index can
 *     still fetch its chunks. That is what makes this safe.
 *   • Anything cross-origin is not our business: Supabase, Photon, Stripe and
 *     the image hosts all pass straight through, untouched and uncached. A
 *     cached API response is a wrong answer with a long life.
 *   • /version.json is never cached. The deploy verifies the live build through
 *     it, and a cached copy would have the deploy confirm itself.
 *
 * KILL SWITCH. If this ever misbehaves, deploy a /sw.js whose whole body is
 *   self.addEventListener('install', () => self.skipWaiting())
 *   self.addEventListener('activate', (e) => e.waitUntil(
 *     self.registration.unregister().then(() => self.clients.matchAll())
 *       .then((cs) => cs.forEach((c) => c.navigate(c.url)))))
 * Browsers revalidate sw.js on every navigation (and at most every 24h), so the
 * replacement reaches people without them doing anything.
 */

// Bump to drop every previous cache. Only needed if the strategies below
// change; a new BUILD of the site does not need it, because asset URLs are
// content-hashed and the shell is network-first.
const CACHE = 'sustainalists-v1'

// The shell, so a cold offline start has something to render.
const SHELL = '/index.html'

self.addEventListener('install', (event) => {
  event.waitUntil(
    caches.open(CACHE)
      .then((c) => c.add(new Request(SHELL, { cache: 'reload' })))
      // A failed precache must not block installation — the worker is still
      // useful, it just has no offline shell until the first navigation.
      .catch(() => {})
      .then(() => self.skipWaiting()),
  )
})

self.addEventListener('activate', (event) => {
  event.waitUntil(
    caches.keys()
      .then((keys) => Promise.all(keys.filter((k) => k !== CACHE).map((k) => caches.delete(k))))
      .then(() => self.clients.claim()),
  )
})

// NOT '/icons/'. That path is an Apache Alias in the stock config — it points
// at the server's own mod_autoindex icon set, outside the web root, with
// AllowOverride None. Files uploaded to public/icons/ land on disk and are
// never served: the alias shadows them, .htaccess does not apply, so the SPA
// rewrite never sees the request and every one 404s. Hence app-icons/.
const isAsset = (url) => url.pathname.startsWith('/assets/')
  || url.pathname.startsWith('/app-icons/')
  || url.pathname === '/favicon.svg'

self.addEventListener('fetch', (event) => {
  const { request } = event
  if (request.method !== 'GET') return

  const url = new URL(request.url)
  // Same-origin only. Everything else — Supabase, Photon, Stripe, image hosts —
  // goes to the network as if this worker did not exist.
  if (url.origin !== self.location.origin) return
  // The deploy asks the site what it is running. Never answer from a cache.
  if (url.pathname === '/version.json') return

  // Navigations: network first, cache only as an offline fallback.
  if (request.mode === 'navigate') {
    event.respondWith(
      fetch(request)
        .then((res) => {
          const copy = res.clone()
          caches.open(CACHE).then((c) => c.put(SHELL, copy)).catch(() => {})
          return res
        })
        .catch(() => caches.match(SHELL).then((r) => r ?? Response.error())),
    )
    return
  }

  // Hashed, immutable assets: serve from cache, fill it on first miss.
  if (isAsset(url)) {
    event.respondWith(
      caches.match(request).then((hit) => hit ?? fetch(request).then((res) => {
        if (res.ok) {
          const copy = res.clone()
          caches.open(CACHE).then((c) => c.put(request, copy)).catch(() => {})
        }
        return res
      })),
    )
  }
  // Everything else same-origin (sitemap, robots, og images, the howto pages)
  // is left alone: no cache entry, no interception.
})
