let daemonUrl = null;

function jsonError(code, status) {
  return new Response(JSON.stringify({ error: { code, message: code } }), {
    status,
    headers: { "content-type": "application/json;charset=UTF-8" },
  });
}

function shouldProxy(url) {
  return url.origin === self.location.origin && (url.pathname.startsWith("/api/") || url.pathname.startsWith("/artifacts/"));
}

self.addEventListener("install", (event) => {
  event.waitUntil(self.skipWaiting());
});

self.addEventListener("activate", (event) => {
  event.waitUntil(self.clients.claim());
});

self.addEventListener("message", (event) => {
  if (event.data?.type !== "W3KITS_DAEMON_PROXY_SET_TARGET") return;
  try {
    const target = new URL(event.data.daemonUrl);
    daemonUrl = target.toString();
  } catch {
    daemonUrl = null;
  }
});

self.addEventListener("fetch", (event) => {
  const url = new URL(event.request.url);
  if (!shouldProxy(url)) return;
  event.respondWith((async () => {
    if (!daemonUrl) return jsonError("w3kits_opendesign_daemon_not_ready", 503);
    const target = new URL(url.pathname + url.search, daemonUrl);
    return fetch(target, {
      method: event.request.method,
      headers: event.request.headers,
      body: event.request.method === "GET" || event.request.method === "HEAD" ? undefined : event.request.body,
      redirect: "manual",
    });
  })().catch(() => jsonError("w3kits_opendesign_daemon_proxy_failed", 502)));
});
