// Multi-tenant LMS PWA service worker
// Academy storefront: network-only for all document navigations (no stale HTML shell).

const CACHE_NAME = 'launchpad-lms-pwa-v15';
const CORE_ASSETS = ['/icons/icon-192.png', '/icons/icon-512.png'];

function isNextRouterRequest(request, url) {
  if (request.headers.get('RSC') === '1') return true;
  if (request.headers.get('Next-Router-Prefetch')) return true;
  if (request.headers.get('Next-Router-State-Tree')) return true;
  if (request.headers.get('Next-Action')) return true;
  if (url.searchParams.has('_rsc')) return true;
  return false;
}

self.addEventListener('install', (event) => {
  event.waitUntil(
    caches.open(CACHE_NAME).then((cache) =>
      cache.addAll(CORE_ASSETS).catch((err) => {
        console.warn('[sw] core asset precache failed (icons may be missing):', err);
      })
    )
  );
});

self.addEventListener('message', (event) => {
  if (event.data?.type === 'SKIP_WAITING') self.skipWaiting();
});

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

self.addEventListener('fetch', (event) => {
  const { request } = event;
  const url = new URL(request.url);

  if (url.origin !== self.location.origin) {
    event.respondWith(fetch(request));
    return;
  }

  if (
    url.pathname.startsWith('/api') ||
    url.pathname.startsWith('/_next') ||
    isNextRouterRequest(request, url)
  ) {
    event.respondWith(fetch(request));
    return;
  }

  if (url.pathname === '/manifest.webmanifest' || url.pathname.startsWith('/manifest.webmanifest')) {
    event.respondWith(fetch(request));
    return;
  }

  if (request.method !== 'GET') return;

  // Never cache HTML navigations — always fetch fresh document from server.
  if (request.mode === 'navigate' || request.headers.get('accept')?.includes('text/html')) {
    event.respondWith(fetch(request));
    return;
  }

  event.respondWith(
    caches.match(request).then((cached) => {
      if (cached) return cached;
      return fetch(request).then((response) => {
        if (!response || response.status !== 200 || response.type === 'opaque') {
          return response;
        }
        const responseClone = response.clone();
        caches.open(CACHE_NAME).then((cache) => cache.put(request, responseClone));
        return response;
      });
    })
  );
});


