import { env } from "../env";

export function ViewpointAPIClient() {
  const baseUrl = env.GetString("VIEWPOINT_API");
  const token = env.GetString("VIEWPOINT_API_KEY");
  return async function ViewpointFetch<TResponse>(
    path: string,
    init?: RequestInit,
  ): Promise<TResponse | null> {

    const response = await fetch(`${baseUrl}${path}`, {
      ...init,
      headers: {
        ...(init?.headers ?? {}),
        api_key: token,
        Accept: "application/json",
        "Content-Type": "application/json",
      },
    });
    if (!response.ok) {
      console.log(await response.json());
      console.log(
        `Viewpoint API error: ${response.status} ${response.statusText}`,
      );
      return null;
    }

    const contentType = response.headers.get("content-type");

    if (contentType?.includes("application/json")) {
      return (await response.json()) as TResponse;
    }
    return (await response.text()) as TResponse;
  };
}
