// service-worker.js - Must be in the /olms/ directory

// 💡 IMPORTANT: Increment this version number whenever you change the PRECACHE_ASSETS list
const CACHE_VERSION = 'olms-cache-v3'; 
const DYNAMIC_CACHE = 'olms-dynamic-v1';
const OFFLINE_URL = '/olms/index.php?page=offline'; 

// List of all static assets that must be pre-cached
// Ensure every path below exists on your server. Any 404 will break the install!
const PRECACHE_ASSETS = [
    // Primary Pages (Must be cacheable and not immediately redirect)
    '/olms/index.php?page=student_dashboard', 
    '/olms/index.php?page=login',
    // Fallback Page
    OFFLINE_URL,
    // Static Assets
    '/olms/assets/icons/icon-192x192.png',
    '/olms/assets/icons/icon-512x512.png',
    // Default Image (Ensure this file exists at /olms/public/images/!)
    '/olms/public/images/default-course.png', 
    '/olms/favicon.ico',
    // External Assets (Caching external assets is complex, but often necessary)
    'https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css',
];


// 1. INSTALL Event: Caches static assets
self.addEventListener('install', (event) => {
    console.log('[Service Worker] Install initiated. Pre-caching assets...');
    event.waitUntil(
        caches.open(CACHE_VERSION)
        .then((cache) => {
            return cache.addAll(PRECACHE_ASSETS);
        })
        .then(() => self.skipWaiting()) // Forces the new Service Worker to activate immediately
        .catch(error => {
            console.error('[Service Worker] Pre-caching failed (likely a 404):', error);
        })
    );
});

// 2. ACTIVATE Event: Cleans up old caches
self.addEventListener('activate', (event) => {
    console.log('[Service Worker] Activate initiated. Cleaning old caches...');
    event.waitUntil(
        caches.keys().then((cacheNames) => {
            return Promise.all(
                cacheNames.filter((name) => {
                    // Delete old caches that do not match the current version
                    return name !== CACHE_VERSION && name !== DYNAMIC_CACHE;
                }).map((name) => {
                    return caches.delete(name);
                })
            );
        }).then(() => self.clients.claim()) // Takes control of pages immediately
    );
});

// 3. FETCH Event: Serves content based on strategy
self.addEventListener('fetch', (event) => {
    
    // 🛑 CRITICAL FIX: Bypass Service Worker for Logout Requests 🛑
    // This prevents the ERR_FAILED on Android logout redirects.
    if (event.request.url.includes('page=logout')) {
        console.log('[Service Worker] Bypassing cache for logout.');
        event.respondWith(fetch(event.request));
        return; 
    }

    // Strategy for Navigation and Main Pages (Network-First, then Cache, then Offline)
    if (event.request.mode === 'navigate' || event.request.destination === 'document' || event.request.url.includes('index.php')) {
        event.respondWith(
            fetch(event.request)
            .then(response => {
                // Check for valid response that isn't a redirect (status 3xx)
                if (!response || response.status === 404 || response.type === 'opaque') {
                    throw new Error('Network failure or invalid response');
                }
                
                // Cache the fresh response for dynamic pages
                const responseToCache = response.clone();
                caches.open(DYNAMIC_CACHE)
                    .then(cache => {
                        // Only cache successful pages
                        if (response.status === 200) {
                             cache.put(event.request, responseToCache);
                        }
                    });

                return response;
            })
            .catch(() => {
                // If network fails (offline), try to serve from the cache
                return caches.match(event.request)
                .then(response => {
                    if (response) {
                        return response;
                    }
                    // If all fails, serve the generic offline page
                    return caches.match(OFFLINE_URL);
                })
            })
        );
        return;
    } 

    // Strategy for Images, CSS, etc. (Cache-First, then Network)
    event.respondWith(
        caches.match(event.request)
        .then(response => {
            return response || fetch(event.request);
        })
    );
});