/* eslint-disable no-restricted-globals */
/* 简易 PWA Service Worker（兼容 CRA 的 Workbox 注入机制）：
 * - 使用 Workbox 预缓存构建产物（precacheAndRoute(self.__WB_MANIFEST)）
 * - 额外对首页等关键路径做手动预缓存
 * - 对同源的 GET 请求走 cache-first 策略
 */

import { precacheAndRoute } from 'workbox-precaching';

// 由 react-scripts 在构建时注入实际的资源清单
precacheAndRoute(self.__WB_MANIFEST || []);

const CACHE_NAME = 'sproutworkcollect-cache-v1';
const PRECACHE_URLS = ['/', '/index.html'];

self.addEventListener('install', (event) => {
  event.waitUntil(
    caches.open(CACHE_NAME).then((cache) => cache.addAll(PRECACHE_URLS)),
  );
  self.skipWaiting();
});

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

self.addEventListener('fetch', (event) => {
  const { request } = event;

  // 只对 GET 请求、同源请求做缓存处理，其它直接放行
  if (request.method !== 'GET' || new URL(request.url).origin !== self.location.origin) {
    return;
  }

  event.respondWith(
    caches.match(request).then((cached) => {
      if (cached) {
        return cached;
      }
      return fetch(request).then((response) => {
        const responseClone = response.clone();
        caches.open(CACHE_NAME).then((cache) => cache.put(request, responseClone));
        return response;
      });
    }),
  );
});

