// ================================
// CONFIG
// ================================
const cacheVersion = 'v2';
const CACHE_PREFIX = "pwa-qrexOrder"; // Prefix for cache names
const OFFLINE_URL = '/offline.html'; // Actual offline page URL

// Static files to precache (use absolute paths to be safe)
const filesToCache = [
  '/assets/frontend/css/style.css',
  '/uploads/pwa/logo.png',
  OFFLINE_URL
];

// Generate cache name
function getCacheName() {
  return `${CACHE_PREFIX}-${cacheVersion}`;
}

// ================================
// INSTALL EVENT
// ================================
self.addEventListener("install", event => {
  event.waitUntil(
    caches.open(getCacheName()).then(cache => {
      // Try caching each file individually so one failure doesn’t block install
      return Promise.all(
        filesToCache.map(url =>
          fetch(url, { cache: "reload" })
            .then(response => {
              if (!response.ok) {
                throw new Error(`Request for ${url} failed with status ${response.status}`);
              }
              return cache.put(url, response.clone());
            })
            .catch(err => {
              console.warn(`⚠️ Failed to cache ${url}:`, err);
            })
        )
      );
    })
  );
  self.skipWaiting(); // activate worker immediately after install
});

// ================================
// ACTIVATE EVENT
// ================================
self.addEventListener('activate', event => {
  event.waitUntil(
    caches.keys().then(cacheNames => {
      return Promise.all(
        cacheNames
          .filter(cacheName => cacheName.startsWith(CACHE_PREFIX) && cacheName !== getCacheName())
          .map(cacheName => caches.delete(cacheName))
      );
    })
  );
  self.clients.claim(); // take control of all pages immediately
});

// ================================
// FETCH EVENT
// ================================
self.addEventListener("fetch", event => {
  // Don’t cache non-GET requests (like POST/PUT)
  if (event.request.method !== 'GET') {
    return;
  }

  event.respondWith(
    caches.match(event.request).then(response => {
      if (response) {
        return response; // return cached response
      }

      // Otherwise, fetch from network
      return fetch(event.request).then(networkResponse => {
        // Cache only successful responses
        if (!networkResponse || networkResponse.status !== 200 || networkResponse.type !== 'basic') {
          return networkResponse;
        }

        // Save a clone in cache for later
        let responseClone = networkResponse.clone();
        caches.open(getCacheName()).then(cache => {
          cache.put(event.request, responseClone);
        });

        return networkResponse;
      }).catch(() => {
        // If both cache + network fail → show offline page for HTML requests
        if (event.request.mode === 'navigate') {
          return caches.match(OFFLINE_URL);
        }
      });
    })
  );
});
