/* eslint-disable @typescript-eslint/no-unused-vars */

const CACHE_NAME = "pwa-cache-v2";

// نصب Service Worker
self.addEventListener("install", (event) => {
  console.log("Service Worker installing...");

  event.waitUntil(
    caches.open(CACHE_NAME).then((cache) => {
      return cache.addAll([
        "/",
        "/manifest.json",
        "/images/icons/256x256.png",
        "/images/icons/512x512.png",
      ]);
    })
  );
  self.skipWaiting();
});

// فعال‌سازی Service Worker
self.addEventListener("activate", (event) => {
  console.log("Service Worker activated.");
  event.waitUntil(
    caches.keys().then((keys) =>
      Promise.all(
        keys
          .filter((key) => key !== CACHE_NAME)
          .map((key) => caches.delete(key))
      )
    ).then(() => self.clients.claim())
  );
});

// هندل درخواست‌ها
  self.addEventListener("fetch", (event) => {
    const url = new URL(event.request.url);

    // استراتژی network-first برای درخواست‌های HTML (navigation requests)
    if (event.request.mode === "navigate") {
      event.respondWith(
        fetch(event.request)
          .then(async (response) => {
            const cache = await caches.open(CACHE_NAME);
            await cache.put(event.request, response.clone());
            return response;
          })
          .catch(() => caches.match(event.request))
      );
      return;
    }

    // آیکون‌ها: network-first تا تغییرات فوری اعمال شوند
  if (url.pathname.startsWith("/images/icons/")) {
    event.respondWith(
      fetch(event.request)
        .then((res) => {
          if (res.ok) {
            const clone = res.clone();
            caches.open(CACHE_NAME).then((cache) => cache.put(event.request, clone));
          }
          return res;
        })
        .catch(() => caches.match(event.request))
    );
    return;
  }

  // سایر فایل‌های استاتیک: stale-while-revalidate
  if (
    url.pathname.startsWith("/images/") ||
    url.pathname.endsWith(".png") ||
    url.pathname.endsWith(".jpg") ||
    url.pathname.endsWith(".jpeg") ||
    url.pathname.endsWith(".gif") ||
    url.pathname.endsWith(".webp") ||
    url.pathname.endsWith("manifest.json")
  ) {
    event.respondWith(
      caches.match(event.request).then((cached) => {
        const networkFetch = fetch(event.request).then((res) => {
          if (res.ok) {
            const clone = res.clone();
            caches.open(CACHE_NAME).then((cache) => cache.put(event.request, clone));
          }
          return res;
        });
        return cached || networkFetch;
      })
    );
  }
});
