// Digital Birhan ERP - Service Worker
const CACHE_NAME = 'birhan-erp-v1.0.0';
const urlsToCache = [
    '/',
    '/index.html',
    '/style.css',
    '/app.js',
    '/manifest.json',
    '/libs/storage.js',
    '/libs/utils.js',
    '/libs/notifications.js',
    '/libs/barcode.js',
    '/libs/pdfExport.js',
    '/libs/excelExport.js',
    '/modules/dashboard.js',
    '/modules/crm.js',
    '/modules/quotations.js',
    '/modules/invoices.js',
    '/modules/inventory.js',
    '/modules/suppliers.js',
    '/modules/projects.js',
    '/modules/production.js',
    '/modules/installation.js',
    '/modules/expenses.js',
    '/modules/payments.js',
    '/modules/reports.js',
    '/modules/tasks.js',
    '/modules/calendar.js',
    '/modules/trash.js',
    '/modules/documents.js',
    '/modules/settings.js'
];

// Install Service Worker
self.addEventListener('install', event => {
    event.waitUntil(
        caches.open(CACHE_NAME)
            .then(cache => {
                console.log('Opened cache');
                return cache.addAll(urlsToCache);
            })
    );
});

// Fetch with cache fallback
self.addEventListener('fetch', event => {
    event.respondWith(
        caches.match(event.request)
            .then(response => {
                if (response) {
                    return response;
                }
                return fetch(event.request)
                    .then(response => {
                        if (!response || response.status !== 200 || response.type !== 'basic') {
                            return response;
                        }
                        const responseToCache = response.clone();
                        caches.open(CACHE_NAME)
                            .then(cache => {
                                cache.put(event.request, responseToCache);
                            });
                        return response;
                    });
            })
    );
});

// Activate and clean old caches
self.addEventListener('activate', event => {
    const cacheWhitelist = [CACHE_NAME];
    event.waitUntil(
        caches.keys().then(cacheNames => {
            return Promise.all(
                cacheNames.map(cacheName => {
                    if (cacheWhitelist.indexOf(cacheName) === -1) {
                        return caches.delete(cacheName);
                    }
                })
            );
        })
    );
});