/// <reference lib="webworker" />

import { precacheAndRoute, cleanupOutdatedCaches } from 'workbox-precaching';
import { registerRoute, NavigationRoute } from 'workbox-routing';
import { createHandlerBoundToURL } from 'workbox-precaching';
import { clientsClaim } from 'workbox-core';
import db from './bookDatabase';

declare let self: ServiceWorkerGlobalScope;

precacheAndRoute(self.__WB_MANIFEST);

cleanupOutdatedCaches();

let allowlist: RegExp[] | undefined;
if (import.meta.env.DEV) allowlist = [/^\/$/];

registerRoute(
  new NavigationRoute(createHandlerBoundToURL('index.html'), { allowlist }),
);

self.addEventListener('fetch', (event) => {
  const url = new URL(event.request.url);

  if (url.pathname === '/books') {
    event.respondWith(handleBooksRequest(event.request));
  }
});

async function handleBooksRequest(request: Request) {
  try {
    const response = await fetch(request);
    const data = await response.clone().json();

    await db.books.clear();
    await db.books.bulkAdd(data);

    return response;
  } catch (err) {
    const books = await db.books.toArray();
    return new Response(JSON.stringify(books), {
      headers: { 'Content-Type': 'application/json' },
    });
  }
}

self.skipWaiting();
clientsClaim();

