const CACHE_NAME = 'agh-health-card-v2';

const STATIC_ASSETS = [
    './manifest.json',
    './favicon.png',
    './assets/icons/icon-192.png',
    './assets/icons/icon-512.png'
];

self.addEventListener('install', event => {
    event.waitUntil(
        caches.open(CACHE_NAME).then(cache => {
            return Promise.all(
                STATIC_ASSETS.map(asset => {
                    return cache.add(asset).catch(error => {
                        console.log('Cache failed:', asset, error);
                    });
                })
            );
        })
    );

    self.skipWaiting();
});

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

    self.clients.claim();
});

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

    if (request.method !== 'GET') return;

    event.respondWith(
        fetch(request)
            .then(response => response)
            .catch(() => caches.match(request))
    );
});
