/* =====================================================
   SERVICE WORKER – ANGEBOTS & AUFTRAGS APP
   ===================================================== */

const CACHE_NAME = "angebot-app-v1";

/* Dateien, die offline verfügbar sein dürfen */
const STATIC_ASSETS = [
  "/app/public/style.css",
  "/app/public/app.js",
  "/app/public/manifest.json",
  "/app/public/assets/logo.png",
  "/app/public/icons/icon-192.png",
  "/app/public/icons/icon-512.png"
];

/* -----------------------------
   INSTALL
----------------------------- */
self.addEventListener("install", event => {
  event.waitUntil(
    caches.open(CACHE_NAME).then(cache => {
      return cache.addAll(STATIC_ASSETS);
    })
  );
  self.skipWaiting();
});

/* -----------------------------
   ACTIVATE
----------------------------- */
self.addEventListener("activate", event => {
  event.waitUntil(
    caches.keys().then(keys =>
      Promise.all(
        keys.map(key => {
          if (key !== CACHE_NAME) {
            return caches.delete(key);
          }
        })
      )
    )
  );
  self.clients.claim();
});

/* -----------------------------
   FETCH
   - Offline nur für statische Dateien
   - API & PHP immer live
----------------------------- */
self.addEventListener("fetch", event => {

  /* Nur GET-Anfragen cachen */
  if (event.request.method !== "GET") {
    return;
  }

  /* API & Login niemals cachen */
  if (
    event.request.url.includes("/api/") ||
    event.request.url.includes("/auth/") ||
    event.request.url.endsWith(".php")
  ) {
    return;
  }

  event.respondWith(
    caches.match(event.request).then(response => {
      return response || fetch(event.request);
    })
  );
});

/* -----------------------------
   PUSH BENACHRICHTIGUNGEN
----------------------------- */
self.addEventListener("push", event => {
  if (!event.data) return;

  const data = event.data.json();

  self.registration.showNotification(
    data.title || "Angebots-App",
    {
      body: data.body || "",
      icon: "/app/public/icons/icon-192.png",
      badge: "/app/public/icons/icon-192.png",
      data: data.url || "/app/"
    }
  );
});

/* -----------------------------
   PUSH KLICK
----------------------------- */
self.addEventListener("notificationclick", event => {
  event.notification.close();

  event.waitUntil(
    clients.openWindow(event.notification.data)
  );
});
