import { userService } from "../services/user.service";

export const fetchWrapper = {
	get: request("GET"),
	post: request("POST"),
	put: request("PUT"),
	delete: request("DELETE"),
};

function request(method) {
	return (url, body) => {
		const isFormData = body instanceof FormData;
		const headers = authHeader(url);
		
		if (!isFormData && body) {
			headers["Content-Type"] = "application/json";
		}

		const requestOptions = {
			method,
			headers,
			body: isFormData
				? body
				: body
				? JSON.stringify(body)
				: undefined,
		};

		return fetch(url, requestOptions).then(handleResponse);
	};
}

function authHeader(url) {
	const user = userService.userValue;
	return user ? { Authorization: `Bearer ${user.token}` } : {};
}

async function handleResponse(response) {
	const isJson = response.headers
		?.get("content-type")
		?.includes("application/json");
	const data = isJson ? await response.json() : null;

	if (!response.ok) {
		if ([401, 403].includes(response.status) && userService.userValue) {
			userService.logout();
		}
		const error = (data && data.message) || response.statusText;
		return Promise.reject(error);
	}

	return data;
}
