import { apiUrl } from "./base";

export class ApiError extends Error {
	constructor(
		message: string,
		public status?: number,
	) {
		super(message);
		this.name = "ApiError";
	}
}

export async function apiFetch<T>(url: string, init?: RequestInit): Promise<T> {
	const res = await fetch(apiUrl(url), init);
	const data = (await res.json().catch(() => ({}))) as T & { error?: string };
	if (!res.ok || (data && "error" in data && data.error)) {
		throw new ApiError((data as { error?: string }).error || res.statusText, res.status);
	}
	return data;
}

export async function apiPost<T>(url: string, body?: unknown): Promise<T> {
	return apiFetch<T>(url, {
		method: "POST",
		headers: { "Content-Type": "application/json" },
		body: body !== undefined ? JSON.stringify(body) : undefined,
	});
}

export async function apiGet<T>(url: string): Promise<T> {
	return apiFetch<T>(url);
}
