const BUNGEE_LITE_PUBLIC_AFFILIATE_ID =
	"609913096e1b3962cecd0ee5cd3d95f618d6a49af0fe870fef0faf88ff367039708902197e0b2b78b1d76cb0837ad0b318baedceb5fef75aad43e6cb";
// biome-ignore lint/suspicious/noExplicitAny: <explanation>
export function bungeeApiFetcher<T = any>({
	query,
	apiKey,
	body,
	method = "GET",
	affiliateId,
}: {
	query: string;
	apiKey?: string;
	body?: string;
	method?: "GET" | "POST";
	affiliateId: string | undefined;
}) {
	if (!apiKey) {
		throw new Error("API Key is required for bungeeApiFetcher");
	}

	let headers: Record<string, string> = {
		"x-api-key": apiKey,
		affiliate: affiliateId || BUNGEE_LITE_PUBLIC_AFFILIATE_ID,
	};
	if (body && method === "POST") {
		headers = {
			...headers,
			"Content-Type": "application/json",
		};
	}

	return fetch(query, { headers, body, method }).then((res) => {
		if (!res.ok) {
			return res.json().then((errorData) => {
				console.log("error data: ", errorData);
				const errorMessage = errorData.message || "An error occurred";

				throw new Error(`${res.status}: ${errorMessage}`);
			});
		}
		return res.json() as Promise<T>;
	});
}
