/**
 * VideoKonverter TV - Service Worker (minimal)
 * Ermoeglicht PWA-Installation auf Handys und Tablets
 * Kein Offline-Caching noetig (Streaming braucht Netzwerk)
 */

const CACHE_NAME = "vk-tv-v17";
const STATIC_ASSETS = [
    "/static/tv/css/tv.css",
    "/static/tv/js/tv.js",
    "/static/tv/js/player.js",
    "/static/tv/js/vknative-bridge.js",
    "/static/tv/icons/icon-192.png",
];

// Installation: Statische Assets cachen
self.addEventListener("install", (event) => {
    event.waitUntil(
        caches.open(CACHE_NAME)
            .then(cache => cache.addAll(STATIC_ASSETS))
            .then(() => self.skipWaiting())
    );
});

// Aktivierung: Alte Caches aufraemen
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())
    );
});

// Fetch: Network-First Strategie (Streaming braucht immer Netzwerk)
self.addEventListener("fetch", (event) => {
    // Nur GET-Requests cachen
    if (event.request.method !== "GET") return;

    // API-Requests und Streaming nie cachen
    const url = new URL(event.request.url);
    if (url.pathname.startsWith("/api/") || url.pathname.startsWith("/tv/api/")
        || url.pathname.includes("/stream") || url.pathname.includes("/direct-stream")) {
        return;
    }

    // Statische Assets: Cache-First
    if (url.pathname.startsWith("/static/tv/")) {
        event.respondWith(
            caches.match(event.request)
                .then(cached => cached || fetch(event.request)
                    .then(response => {
                        const clone = response.clone();
                        caches.open(CACHE_NAME)
                            .then(cache => cache.put(event.request, clone));
                        return response;
                    })
                )
        );
        return;
    }

    // Alles andere: Network-First
    event.respondWith(
        fetch(event.request)
            .catch(() => caches.match(event.request))
    );
});
