// CNPERP Service Worker — installable app; HTML/JS always network-first so deploys show without hard refresh
const CACHE = 'cnperp-v9';
const OFFLINE_URLS = [
  '/static/cnp-solutions.html',
  '/static/manifest.json',
  '/static/icons/icon-192.png',
  '/static/icons/icon-512.png',
];

function isApiRequest(url) {
  return url.includes('/api/');
}

function isNetworkFirstAsset(url) {
  if (url.includes('/api/')) return false;
  try {
    const path = new URL(url, self.location.origin).pathname;
    if (path.endsWith('.html')) return true;
    if (path.startsWith('/static/js/')) return true;
    if (path === '/static/sw.js') return true;
    return false;
  } catch {
    return false;
  }
}

function networkFirst(request, offlineFallback) {
  return fetch(request)
    .then((response) => {
      if (response && response.ok && request.method === 'GET') {
        const clone = response.clone();
        caches.open(CACHE).then((cache) => cache.put(request, clone)).catch(() => {});
      }
      return response;
    })
    .catch(() =>
      caches.match(request).then((cached) => {
        if (cached) return cached;
        if (offlineFallback) return caches.match(offlineFallback);
        return new Response('Offline', { status: 503, statusText: 'Offline' });
      })
    );
}

self.addEventListener('install', (e) => {
  e.waitUntil(
    caches.open(CACHE).then((c) => c.addAll(OFFLINE_URLS)).then(() => self.skipWaiting())
  );
});

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

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

self.addEventListener('fetch', (e) => {
  const url = e.request.url;

  if (isApiRequest(url)) {
    e.respondWith(
      fetch(e.request).catch(() =>
        new Response(
          JSON.stringify({ success: false, error: { message: 'Network unavailable — server unreachable' } }),
          { status: 503, headers: { 'Content-Type': 'application/json' } }
        )
      )
    );
    return;
  }

  // Navigations and ERP pages/scripts: always try network first (fixes stale dashboard after deploy)
  if (e.request.mode === 'navigate' || isNetworkFirstAsset(url)) {
    e.respondWith(networkFirst(e.request, '/static/cnp-solutions.html'));
    return;
  }

  // Icons, vendor bundles: cache-first is fine
  e.respondWith(
    caches.match(e.request).then(
      (cached) =>
        cached ||
        fetch(e.request).then((response) => {
          if (response && response.ok && e.request.method === 'GET') {
            const clone = response.clone();
            caches.open(CACHE).then((cache) => cache.put(e.request, clone)).catch(() => {});
          }
          return response;
        }).catch(() => caches.match('/static/cnp-solutions.html'))
    )
  );
});
