import { API_URL } from "@/lib/constants";
import { ApiResponse } from "@/types/types";
import { getApiUrl } from "@/utils/api";
import { getCookie } from "cookies-next";
import { ReadonlyRequestCookies } from "next/dist/server/web/spec-extension/adapters/request-cookies";
export default async function request<T>(
	endpoint: string,
	options: {
		method?: "GET" | "POST" | "PATCH" | "DELETE";
		body?: any;
		requiresAuth?: boolean;
		csrfToken?: boolean;
		cookies?: () => Promise<ReadonlyRequestCookies>;
	} = {},
): Promise<ApiResponse<T>> {
	console.log(API_URL, endpoint);
	const { method = "GET", body, requiresAuth = true } = options;
	const headers: Record<string, string> = {
		"Content-Type": "application/json",
	};

	if (options.csrfToken) {
		const res: ApiResponse<{ csrf: string }> = await (
			await fetch(`${getApiUrl()}/csrf-token`, { credentials: "include" })
		).json();
		if (res.data) headers["X-CSRF-Token"] = res.data.csrf;
	}

	if (requiresAuth) {
		let authToken;
		if (!options.cookies) {
			authToken = getCookie("auth_token");
		} else {
			authToken = (await options.cookies()).get("auth_token")?.value;
		}

		if (!authToken) {
			throw new Error("User is not authenticated");
		}
		headers.Authorization = `Bearer ${authToken}`;
	}

	const response = await fetch(`${getApiUrl()}${endpoint}`, {
		method,
		headers,
		body: body ? JSON.stringify(body) : undefined,
		credentials: options.csrfToken ? "include" : "omit",
	});

	const apiResponse: ApiResponse<T> = await response.json();

	return apiResponse;
}
