const CACHE_NAME = 'site-completo-v1';

// Use URLs completas, geradas pelo PHP, sem alterar (evite só path)
const PRE_CACHE_VIDEOS = [
  'https://barreiras.incodder.com/wp-content/uploads/sites/2/2024/06/barreiras-melhor-cidade-da-bahia-360p.mp4',
];

const ASSETS_PRE_CACHE = [
  '/',
  '/index.html',
];

const FILES_TO_CACHE = [...ASSETS_PRE_CACHE, ...PRE_CACHE_VIDEOS];

self.addEventListener('install', event => {
  event.waitUntil(
    caches.open(CACHE_NAME).then(cache => {
      return cache.addAll(FILES_TO_CACHE);
    })
  );
  self.skipWaiting();
});

self.addEventListener('activate', event => {
  event.waitUntil(
    caches.keys().then(keys =>
      Promise.all(
        keys.map(key => {
          if (key !== CACHE_NAME) {
            return caches.delete(key);
          }
        })
      )
    )
  );
  self.clients.claim();
});

self.addEventListener('fetch', event => {
  event.respondWith(
    caches.match(event.request).then(async cacheResponse => {
      if (cacheResponse) {
        return cacheResponse;
      }
      try {
        const fetchResponse = await fetch(event.request);
        // Só cacheia GET, status 200 e resposta não opaque (com CORS)
        if (
          event.request.method === 'GET' &&
          fetchResponse.status === 200 &&
          fetchResponse.type !== 'opaque'
        ) {
          const cloned = fetchResponse.clone();
          const cache = await caches.open(CACHE_NAME);
          await cache.put(event.request, cloned);
        }
        return fetchResponse;
      } catch (error) {
        // Se não tiver conexão, tenta devolver index.html para rota SPA
        if (event.request.destination === 'document') {
          return caches.match('/index.html');
        }
        // Resposta offline padrão para outros recursos
        return new Response("Recurso indisponível offline.", {
          status: 503,
          statusText: 'Offline'
        });
      }
    })
  );
});
