self.addEventListener("push", onPush);

async function onPush(event) {
  if (event.data) {
    const data = event.data.json();
    const { title, ...rest } = data;

    // Send the push data to the application
    const clients = await self.clients.matchAll();
    clients.forEach((client) => client.postMessage(data));

    await event.waitUntil(
      self.registration.showNotification(title, {
        ...rest,
      })
    );
  }
}

const BASE_URL = "https://khollise.fr";

self.addEventListener("notificationclick", function (event) {
  const clickedNotification = event.notification;
  clickedNotification.close();
  const data = clickedNotification.data || {};

  if (event.action == "open" && data.id) {
    const promiseChain = clients.openWindow(
      BASE_URL + "/colles/" + data.id
    );
    event.waitUntil(promiseChain);
  } else {
    const promiseChain = clients.openWindow(BASE_URL);
    event.waitUntil(promiseChain);
  }
});
