import { QueryClient } from '@tanstack/vue-query';

export async function clearCache() {
  // Clear localStorage and sessionStorage (this also clears persisted Vuex and Pinia data)
  console.log('[Cache] Clearing localStorage...');
  localStorage.clear();
  console.log('[Cache] localStorage cleared.');

  console.log('[Cache] Clearing sessionStorage...');
  sessionStorage.clear();
  console.log('[Cache] sessionStorage cleared.');

  // Clear TanStack Query cache (in-memory)
  try {
    console.log('[Cache] Clearing TanStack Query cache...');
    const queryClient = new QueryClient();
    queryClient.clear();
    console.log('[Cache] TanStack Query cache cleared.');
  } catch (e) {
    console.log('[Cache] TanStack Query not used or error clearing cache.', e);
  }

  // Clear Service Worker cache and force update (Workbox/PWA)
  if ('serviceWorker' in navigator) {
    try {
      console.log('[Cache] Getting Service Worker cache names...');
      const cacheNames = await caches.keys();
      const appCacheNames = cacheNames.filter((name) => name.startsWith('workbox-') || name.includes('api-cache') || name.includes('precache') || name.includes('runtime'));
      console.log('[Cache] Deleting app-related caches:', appCacheNames);
      await Promise.all(appCacheNames.map((name) => caches.delete(name)));
      console.log('[Cache] App-related caches deleted.');

      // Update and activate waiting Service Workers
      console.log('[Cache] Getting Service Worker registrations...');
      const registrations = await navigator.serviceWorker.getRegistrations();
      await Promise.all(
        registrations.map(async (reg) => {
          if (reg.waiting) {
            console.log('[Cache] Sending SKIP_WAITING to Service Worker:', reg);
            reg.waiting.postMessage({ type: 'SKIP_WAITING' });
          }
          console.log('[Cache] Updating Service Worker registration...');
          await reg.update();
        })
      );
      console.log('[Cache] Service Worker registrations updated.');
    } catch (e) {
      console.log('[Cache] Service Worker not used or update failed.', e);
    }
  }

  console.log('[Cache] Reloading window...');
  window.location.reload();
}
