const CACHE_NAME = 'whisky-vault-v2'; // Increment version to force update
const ASSETS_TO_CACHE = [
    '/manifest.json',
    '/icon-192.png',
    '/icon-512.png',
    '/favicon.ico',
];

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

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

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

    // CRITICAL: Always bypass cache for auth, api, and supabase requests
    const isAuthRequest = url.pathname.includes('/auth/') ||
        url.pathname.includes('/v1/auth/') ||
        url.pathname.includes('/v1/token');
    const isApiRequest = url.pathname.includes('/api/');
    const isSupabaseRequest = url.hostname.includes('supabase.co');

    if (isAuthRequest || isApiRequest || isSupabaseRequest) {
        // console.log('[SW] Bypassing cache for:', url.pathname);
        return;
    }

    // Network first for all other requests, especially navigation
    event.respondWith(
        fetch(event.request)
            .then((response) => {
                // Optionally cache successful GET requests for assets
                if (
                    event.request.method === 'GET' &&
                    response.status === 200 &&
                    (url.pathname.startsWith('/_next/static/') || ASSETS_TO_CACHE.includes(url.pathname))
                ) {
                    const responseClone = response.clone();
                    caches.open(CACHE_NAME).then((cache) => {
                        cache.put(event.request, responseClone);
                    });
                }
                return response;
            })
            .catch((err) => {
                if (event.request.mode === 'navigate') {
                    console.log('[SW] Navigation failed, attempting cache fallback for:', url.pathname);
                }
                return caches.match(event.request);
            })
    );
});
