import { readFileSync } from "node:fs";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";

const dir = dirname(fileURLToPath(import.meta.url));
const wasmPath = join(dir, "juicebox-sdk_bg.wasm");

let authTokenResolver = () => {
  throw new Error("juicebox: auth-token resolver not set");
};
export function setAuthTokenResolver(fn) {
  authTokenResolver = fn;
}

globalThis.JuiceboxGetAuthToken = (realmId) => Promise.resolve(authTokenResolver(realmId));

const origFetch = globalThis.fetch.bind(globalThis);
globalThis.fetch = (input, init) => {
  const url = typeof input === "string" ? input : (input?.url ?? String(input));
  if (url.includes("juicebox-sdk_bg") && url.endsWith(".wasm")) {
    return Promise.resolve(
      new Response(readFileSync(wasmPath), { headers: { "Content-Type": "application/wasm" } }),
    );
  }
  return origFetch(input, init);
};

const glue = await import("./sdk.js");

export const { Client, Configuration, RecoverError, RecoverErrorReason } = glue;
