const _apiRoot = "https://ai-api.cytonic.com";
export class ApiError extends Error {
	constructor(description: string, error: string, trace_id: string) {
		super(error);
		this.name = "ApiError";
		this.message = description;
		this.stack = trace_id;
		this.cause = error;
	}
}

async function request(
	entrypoint: string,
	method: "POST" | "GET" = "GET",
	body?: object,
) {
	const apiRoot = localStorage.getItem("API_ROOT") || _apiRoot;
	const address =
		apiRoot + (entrypoint[0] === "/" ? entrypoint : `/${entrypoint}`);

	const res = await fetch(address, {
		method,
		body: JSON.stringify(body),
		headers: {
			...(body && { "Content-Type": "application/json" }),
		},
	});

	if (!res.ok) {
		const error = await res.json();
		throw new ApiError(error.description, error.error, error.trace_id);
	}

	return await res.json();
}

const api = {
	get(
		entrypoint: string,
		queryObj?: string | URLSearchParams | Record<string, string> | string[][],
	) {
		let queryStr = "";
		if (queryObj) queryStr = `?${new URLSearchParams(queryObj).toString()}`;
		return request(entrypoint + queryStr);
	},
	post(entrypoint: string, body?: object) {
		return request(entrypoint, "POST", body);
	},
};

export { api };
