// Backup Service Worker for MYP Platform
const CACHE_NAME = 'myp-platform-backup-v1';

// Assets to cache
const ASSETS_TO_CACHE = [
  '/',
  '/dashboard',
  '/static/css/tailwind.min.css',
  '/static/css/tailwind-dark.min.css',
  '/static/js/ui-components.js',
  '/static/js/offline-app.js',
  '/static/favicon.ico'
];

// Install event - cache core assets
self.addEventListener('install', (event) => {
  console.log('Backup SW: Installing...');
  
  event.waitUntil(
    caches.open(CACHE_NAME)
      .then((cache) => {
        console.log('Backup SW: Caching assets');
        return cache.addAll(ASSETS_TO_CACHE);
      })
      .then(() => {
        console.log('Backup SW: Assets cached');
        return self.skipWaiting();
      })
  );
});

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

// Fetch event - cache first, network fallback
self.addEventListener('fetch', (event) => {
  event.respondWith(
    caches.match(event.request)
      .then((response) => {
        if (response) {
          return response;
        }
        
        return fetch(event.request)
          .then((fetchResponse) => {
            // Don't cache non-success responses
            if (!fetchResponse || fetchResponse.status !== 200 || fetchResponse.type !== 'basic') {
              return fetchResponse;
            }
            
            // Cache successful responses
            const responseToCache = fetchResponse.clone();
            caches.open(CACHE_NAME)
              .then((cache) => {
                cache.put(event.request, responseToCache);
              });
              
            return fetchResponse;
          });
      })
  );
}); 