/*
 * ValuSafe Service Worker v4.1
 *
 * Strategie:
 *   Cache First  — statische Assets (CSS, JS, Icons, Fonts)
 *   Network Only — alle PHP-Seiten, Backend, Login, AJAX, API
 *
 * Cache-Invalidierung: CACHE_VERSION bei jedem Deployment hochzählen.
 */

const CACHE_VERSION = 'valusafe-v4.1';

const STATIC_ASSETS = [
    '/css/cloud.css',
    '/css/dark.css',
    '/css/sand.css',
    '/css/navy.css',
    '/css/forest.css',
    '/css/emerald.css',
    '/css/lavender.css',
    '/css/midnight.css',
    '/css/mint.css',
    '/css/ocean.css',
    '/css/cherry.css',
    '/css/sunset.css',
    '/css/glass.css',
    '/css/next.css',
    '/css/tokens.css',
    '/css/backend.css',
    '/css/tabler-icons.min.css',
    '/js/context_help.js',
    '/js/main.js',
    '/icon-192.png',
    '/icon-512.png',
    '/apple-touch-icon.png',
    '/manifest.json',
];

// ── Install ──────────────────────────────────────────────────
self.addEventListener('install', event => {
    event.waitUntil(
        caches.open(CACHE_VERSION)
            .then(cache => cache.addAll(
                STATIC_ASSETS.filter(url => !url.endsWith('.php'))
            ))
            .then(() => self.skipWaiting())
    );
});

// ── Activate: alte Caches löschen ───────────────────────────
self.addEventListener('activate', event => {
    event.waitUntil(
        caches.keys()
            .then(keys => Promise.all(
                keys
                    .filter(key => key !== CACHE_VERSION)
                    .map(key => {
                        console.log('[SW] Alter Cache gelöscht:', key);
                        return caches.delete(key);
                    })
            ))
            .then(() => self.clients.claim())
    );
});

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

    // Nur eigene Origin behandeln
    if (url.origin !== self.location.origin) return;

    // Nur GET behandeln
    if (event.request.method !== 'GET') return;

    const path = url.pathname;

    // PHP-Dateien und dynamische Routen: SW komplett umgehen
    // (kein event.respondWith → Browser handhabt den Request normal)
    if (
        path.endsWith('.php') ||
        path === '/' ||
        path === '' ||
        path.startsWith('/backend/') ||
        path.startsWith('/ajax/') ||
        path.startsWith('/backups/') ||
        path.startsWith('/upload/') ||
        path.startsWith('/documents/')
    ) {
        return; // Browser übernimmt — kein SW-Eingriff
    }

    // Statische Assets: Cache First
    if (isStaticAsset(path)) {
        event.respondWith(cacheFirst(event.request));
    }

    // Alles andere: Browser übernimmt (kein return mit respondWith)
});

// ── Cache First Strategie ────────────────────────────────────
async function cacheFirst(request) {
    try {
        const cached = await caches.match(request);
        if (cached) return cached;

        const response = await fetch(request);
        if (response.ok) {
            const cache = await caches.open(CACHE_VERSION);
            cache.put(request, response.clone());
        }
        return response;
    } catch {
        return new Response('Asset nicht verfügbar', { status: 503 });
    }
}

function isStaticAsset(path) {
    return (
        path.startsWith('/css/') ||
        path.startsWith('/js/') ||
        path.endsWith('.css') ||
        path.endsWith('.js') ||
        path.endsWith('.png') ||
        path.endsWith('.jpg') ||
        path.endsWith('.webp') ||
        path.endsWith('.svg') ||
        path.endsWith('.woff') ||
        path.endsWith('.woff2') ||
        path.endsWith('.ico') ||
        path === '/manifest.json'
    );
}
