import type { Handle } from "@sveltejs/kit";

type BobbinService = {
	fetch(request: Request): Promise<Response>;
};

export const handle: Handle = async ({ event, resolve }) => {
	// Keep bobbin off the public network. In Cloudflare this is a Worker
	// service binding; the browser only ever sees the web origin.
	if (event.url.pathname === "/xrpc" || event.url.pathname.startsWith("/xrpc/")) {
		const bobbin = (event.platform?.env as { BOBBIN?: BobbinService } | undefined)?.BOBBIN;
		if (bobbin) {
			const upstream = new URL(event.request.url);
			upstream.hostname = "bobbin.internal";
			return bobbin.fetch(new Request(upstream, event.request));
		}
	}

	return resolve(event, {
		// sveltekit blocks atcute fetch handler from reading headers
		// because it assumes backend APIs might return sensitive headers.
		// this happens when during CSR we run a fetch that was the same
		// as one ran during SSR, so sveltekit tries to give that fetch
		// the data we already had.
		// so we allow these headers to have atcute function properly.
		filterSerializedResponseHeaders(name) {
			return name === "content-type" || name === "content-length";
		}
	});
};
