/* Aria Herat ERP — lightweight PWA service worker.
   Makes the app installable and gives it a basic offline shell. It never
   caches API traffic (always live), uses network-first for page navigations
   (so updates flow), and stale-while-revalidate for same-origin static assets.

   Everything below is written relative to the worker's own folder, because the
   app does not live at the root of its domain: on the cPanel it is served from
   /frontend/ while the API sits beside it at /backend/public/. Absolute paths
   cached the wrong site's index page, and — worse — the "never touch the API"
   rule looked for a path beginning /api and so never matched the real one,
   leaving signed-in API replies eligible for the cache. */

const CACHE = 'aria-erp-v2'

/** The folder this worker was served from — the app's own root. */
const ROOT = new URL('./', self.location.href).pathname

const SHELL = ['', 'index.html', 'manifest.json', 'icons/icon.svg'].map((p) => ROOT + p)

self.addEventListener('install', (event) => {
  event.waitUntil(
    caches.open(CACHE)
      // One missing file must not abandon the whole install.
      .then((c) => Promise.allSettled(SHELL.map((p) => c.add(p))))
      .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())
  )
})

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

  const url = new URL(req.url)

  // Cross-origin (map tiles and the like): straight to the network.
  if (url.origin !== self.location.origin) return

  // Anything outside the app's own folder is somebody else's — the API lives
  // next door on the same host and must never be served from a cache.
  if (!url.pathname.startsWith(ROOT) || url.pathname.includes('/api/')) return

  // Page navigations: network-first, fall back to the cached shell offline.
  if (req.mode === 'navigate') {
    event.respondWith(
      fetch(req)
        .then((res) => { cachePut(req, res.clone()); return res })
        .catch(() => caches.match(req).then((r) => r || caches.match(ROOT + 'index.html')))
    )

    return
  }

  // Static assets: stale-while-revalidate.
  event.respondWith(
    caches.match(req).then((cached) => {
      const network = fetch(req).then((res) => { cachePut(req, res.clone()); return res }).catch(() => cached)

      return cached || network
    })
  )
})

function cachePut (req, res) {
  if (res && res.status === 200 && res.type === 'basic') {
    caches.open(CACHE).then((c) => c.put(req, res))
  }
}
