const CACHE_NAME = 'purchase-haat-smarttech-pos-v3';
const scopePath = new URL(self.registration.scope).pathname.replace(/\/$/, '');
const scoped = path => `${scopePath}/${String(path).replace(/^\//, '')}`.replace(/\/{2,}/g, '/');
const OFFLINE_URL = scoped('public/offline.html');
const POS_OFFLINE_URL = scoped('public/pos-offline.html');
const ASSETS = [
  OFFLINE_URL,
  POS_OFFLINE_URL,
  scoped('public/assets/css/purchase-haat.css'),
  scoped('public/assets/css/pos.css'),
  scoped('public/assets/js/pos-core.js'),
  scoped('public/assets/js/pos-scanner.js'),
  scoped('public/assets/js/pos-printer.js'),
  scoped('public/assets/brand/logo.png'),
  scoped('public/assets/brand/icon-192.png'),
  scoped('public/assets/brand/icon-512.png')
];

self.addEventListener('install', event => {
  event.waitUntil(caches.open(CACHE_NAME).then(cache => cache.addAll(ASSETS)));
  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.request;
  if (request.method !== 'GET') return;
  const requestUrl = new URL(request.url);
  if (requestUrl.origin !== self.location.origin) return;

  const apiPath = scoped('api/');
  if (requestUrl.pathname.startsWith(apiPath)) return;

  const assetPath = scoped('public/assets/');
  if (requestUrl.pathname.startsWith(assetPath)) {
    event.respondWith(
      caches.match(request).then(cached => cached || fetch(request).then(response => {
        if (response.ok) caches.open(CACHE_NAME).then(cache => cache.put(request, response.clone()));
        return response;
      }))
    );
    return;
  }

  if (request.mode === 'navigate') {
    event.respondWith(fetch(request).catch(() => {
      if (requestUrl.pathname.startsWith(scoped('pos/'))) return caches.match(POS_OFFLINE_URL);
      return caches.match(OFFLINE_URL);
    }));
  }
});
