// Imported by Workbox's generated service worker. Adds push notification
// handling to the otherwise vanilla precache worker.
//
// Payload format (sent by PortalPushSender):
//   { title: 'kiko's Rabies booster is due', body: '...', url: '/app/home',
//     icon: '/app/icon-192.png', tag: 'vax-12' }
self.addEventListener('push', (event) => {
  let data = {};
  try { data = event.data ? event.data.json() : {}; } catch { data = {}; }

  const title = data.title || 'Pet Portal';
  const options = {
    body:    data.body  || '',
    icon:    data.icon  || '/app/icon-192.png',
    badge:   data.badge || '/app/icon-192.png',
    tag:     data.tag,                // collapses duplicates
    data:    { url: data.url || '/' },
    requireInteraction: data.persistent === true,
  };

  event.waitUntil(self.registration.showNotification(title, options));
});

self.addEventListener('notificationclick', (event) => {
  event.notification.close();
  const targetUrl = event.notification.data?.url || '/';
  event.waitUntil(
    self.clients.matchAll({ type: 'window', includeUncontrolled: true }).then((clientList) => {
      // Reuse an existing tab if one is open at the PWA, else open new.
      for (const client of clientList) {
        if (client.url.includes('/app/') && 'focus' in client) {
          client.navigate(targetUrl);
          return client.focus();
        }
      }
      return self.clients.openWindow(targetUrl);
    })
  );
});
