/* vps-manager Service Worker
 * 缓存策略：
 *  - 预缓存核心静态资源，安装即可离线打开
 *  - 静态资源与页面：stale-while-revalidate（先返回缓存秒开，后台自动拉取最新版本）
 *  - /api/* 数据请求：始终走网络，保证数据实时
 * 更新机制：业务代码更新后，后台自动同步到缓存，下次访问生效；
 *           若需强制刷新缓存，递增 CACHE_NAME 即可清理旧缓存。
 */
const CACHE_NAME = 'vps-manager-v1';

const PRECACHE_URLS = [
  '/',
  '/static/js/vue.global.prod.js',
  '/static/js/tailwind.js',
  '/static/js/api.js',
  '/static/js/app.js',
  '/static/manifest.json',
  '/static/icons/icon-192.png',
  '/static/icons/icon-512.png',
];

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

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

self.addEventListener('fetch', (event) => {
  const request = event.request;
  if (request.method !== 'GET') return;

  const url = new URL(request.url);
  if (url.origin !== self.location.origin) return;
  // 数据接口走网络，不缓存
  if (url.pathname.startsWith('/api/')) return;

  event.respondWith(
    caches.open(CACHE_NAME).then(async (cache) => {
      const cached = await cache.match(request);
      const network = fetch(request)
        .then((response) => {
          if (response && response.ok) cache.put(request, response.clone());
          return response;
        })
        .catch(() => cached);
      return cached || network;
    })
  );
});
