// DBAOps Futuristic Enterprise - Service Worker for Offline Support
const CACHE_NAME = 'dbaops-futuristic-v1';
const OFFLINE_URL = 'offline.html';

// Files to cache for offline use (relative to /mobile/)
const CACHE_FILES = [
    './',
    './index.html',
    './manifest.json',
    './offline.html',
    '../data.json'
];

// Install - cache core files
self.addEventListener('install', (event) => {
    event.waitUntil(
        caches.open(CACHE_NAME)
            .then((cache) => {
                console.log('DBAOps: Caching core files');
                return cache.addAll(CACHE_FILES);
            })
            .then(() => self.skipWaiting())
    );
});

// Activate - clean up old caches
self.addEventListener('activate', (event) => {
    event.waitUntil(
        caches.keys().then((cacheNames) => {
            return Promise.all(
                cacheNames.map((cacheName) => {
                    if (cacheName !== CACHE_NAME) {
                        console.log('DBAOps: Removing old cache', cacheName);
                        return caches.delete(cacheName);
                    }
                })
            );
        }).then(() => self.clients.claim())
    );
});

// Fetch - network first, fall back to cache
self.addEventListener('fetch', (event) => {
    // Skip non-GET requests
    if (event.request.method !== 'GET') return;
    
    // Skip API requests - don't cache these
    if (event.request.url.includes('/api/')) {
        event.respondWith(
            fetch(event.request)
                .catch(() => {
                    return new Response(
                        JSON.stringify({ error: 'Offline', cached: true }),
                        { headers: { 'Content-Type': 'application/json' } }
                    );
                })
        );
        return;
    }
    
    // For other requests, try network first, then cache
    event.respondWith(
        fetch(event.request)
            .then((response) => {
                // Cache successful responses
                if (response.status === 200) {
                    const responseClone = response.clone();
                    caches.open(CACHE_NAME).then((cache) => {
                        cache.put(event.request, responseClone);
                    });
                }
                return response;
            })
            .catch(() => {
                // Network failed, try cache
                return caches.match(event.request)
                    .then((cachedResponse) => {
                        if (cachedResponse) {
                            return cachedResponse;
                        }
                        // Return offline page for navigation requests
                        if (event.request.mode === 'navigate') {
                            return caches.match(OFFLINE_URL);
                        }
                        return new Response('Offline');
                    });
            })
    );
});

// Background sync for incident acknowledgments
self.addEventListener('sync', (event) => {
    if (event.tag === 'sync-acknowledgments') {
        event.waitUntil(syncPendingAcknowledgments());
    }
});

async function syncPendingAcknowledgments() {
    // Get pending acknowledgments from IndexedDB and sync
    console.log('DBAOps: Syncing pending acknowledgments');
}

// Push notifications
self.addEventListener('push', (event) => {
    const data = event.data ? event.data.json() : {};
    
    const options = {
        body: data.body || 'New incident requires attention',
        icon: 'icon-192.png',
        badge: 'badge-72.png',
        vibrate: [200, 100, 200],
        tag: data.incidentId || 'dbaops-notification',
        renotify: true,
        requireInteraction: data.severity === 1,
        data: {
            url: data.url || '/?tab=incidents',
            incidentId: data.incidentId
        },
        actions: [
            { action: 'acknowledge', title: 'Acknowledge' },
            { action: 'view', title: 'View Details' }
        ]
    };
    
    event.waitUntil(
        self.registration.showNotification(data.title || 'DBAOps Alert', options)
    );
});

// Notification click handler
self.addEventListener('notificationclick', (event) => {
    event.notification.close();
    
    if (event.action === 'acknowledge') {
        // Quick acknowledge
        event.waitUntil(
            fetch(`/api/incidents/${event.notification.data.incidentId}/acknowledge`, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ acknowledgedBy: 'Mobile Push' })
            })
        );
    } else {
        // Open the app
        event.waitUntil(
            clients.openWindow(event.notification.data.url)
        );
    }
});
