const CACHE_PREFIX = "facturacion-pwa";
const CACHE_VERSION = "v1";
const STATIC_CACHE = `${CACHE_PREFIX}-${CACHE_VERSION}-static`;
const CACHEABLE_EXTENSIONS = /\.(?:css|js|mjs|png|jpg|jpeg|svg|webp|gif|ico|woff2?|ttf|eot|mp3|wav)$/i;

self.addEventListener("install", function () {
  self.skipWaiting();
});


self.addEventListener("activate", function (event) {
  event.waitUntil(
    caches
      .keys()
      .then(function (keys) {
        return Promise.all(
          keys
            .filter(function (key) {
              return key.startsWith(CACHE_PREFIX) && key !== STATIC_CACHE;
            })
            .map(function (key) {
              return caches.delete(key);
            })
        );
      })
      .then(function () {
        return self.clients.claim();
      })
  );
});

self.addEventListener("fetch", function (event) {
  var request = event.request;
  if (request.method !== "GET") {
    return;
  }

  var requestUrl = new URL(request.url);
  var isSameOrigin = requestUrl.origin === self.location.origin;
  var isPublicAsset = requestUrl.pathname.indexOf("/public/") !== -1;
  var hasCacheableExtension = CACHEABLE_EXTENSIONS.test(requestUrl.pathname);

  if (!isSameOrigin || !isPublicAsset || !hasCacheableExtension) {
    return;
  }

  event.respondWith(
    caches.open(STATIC_CACHE).then(function (cache) {
      return cache.match(request).then(function (cachedResponse) {
        var networkRequest = fetch(request)
          .then(function (networkResponse) {
            if (networkResponse && networkResponse.ok) {
              cache.put(request, networkResponse.clone());
            }
            return networkResponse;
          })
          .catch(function () {
            return cachedResponse;
          });

        if (cachedResponse) {
          event.waitUntil(networkRequest);
          return cachedResponse;
        }

        return networkRequest;
      });
    })
  );
});
