const CACHE_NAME = 'shenze-cache-v1'; // 更新版本号强制更新
const DYNAMIC_CACHE = 'shenze-dynamic-v1';

const STATIC_ASSETS = [
  '/shenze/index.html',
  '/shenze/favicon.ico',
  '/shenze/manifest.json',
  // 避免缓存 version.json
];

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

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

// fetch 事件：合理区分缓存策略
self.addEventListener('fetch', (event) => {
  const url = new URL(event.request.url);

  // version.json 永远走网络
  if (url.pathname === '/shenze/version.json') {
    event.respondWith(
      fetch(event.request)
        .then(response => response)
        .catch(() => new Response('{}', { headers: { 'Content-Type': 'application/json' } }))
    );
    return;
  }

  // index.html 及所有 HTML 页面，网络优先
  if (url.pathname === '/shenze/' || url.pathname.endsWith('.html')) {
    event.respondWith(
      fetch(event.request)
        .then(response => {
          // 更新缓存
          const copy = response.clone();
          caches.open(CACHE_NAME).then(cache => cache.put(event.request, copy));
          return response;
        })
        .catch(() => caches.match(event.request))
    );
    return;
  }

  // 其他静态资源（js/css/img/font等），缓存优先
  event.respondWith(
    caches.match(event.request).then(cachedResponse => {
      return cachedResponse || fetch(event.request).then(networkResponse => {
        if (event.request.method === 'GET' && networkResponse && networkResponse.status === 200) {
          const copy = networkResponse.clone();
          caches.open(DYNAMIC_CACHE).then(cache => cache.put(event.request, copy));
        }
        return networkResponse;
      }).catch(() => {
        return undefined;
      });
    })
  );
});

self.addEventListener('message', event => {
  if (event.data === 'skip-waiting') {
    self.skipWaiting();
  }
});