const CACHE_NAME = 'currypot-shell-v1';

// Cache the assets needed to open the app shell even with a flaky connection.
// API calls (/api/*) are always fetched fresh — menu/prices should never be stale.
const SHELL_ASSETS = [
    self.registration ? self.registration.scope : './',
];

self.addEventListener('install', (event) => {
    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)))
        )
    );
    self.clients.claim();
});

self.addEventListener('fetch', (event) => {
    const url = new URL(event.request.url);

    // Never cache API calls or POST requests — always go to the network for live data.
    if (url.pathname.includes('/api/') || event.request.method !== 'GET') {
        return;
    }

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