import type { ApiErrorResponse } from "@/types/api";

export async function parseApiErrorMessage(response: Response, fallbackMessage: string) {
  try {
    const payload = (await response.json()) as ApiErrorResponse;
    const apiMessage = payload.error?.message?.trim();
    if (!apiMessage) {
      return fallbackMessage;
    }

    const normalizedMessage = apiMessage.toLowerCase();
    if (normalizedMessage === "error" || normalizedMessage === "internal server error") {
      return fallbackMessage;
    }

    return apiMessage;
  } catch {
    return fallbackMessage;
  }
}

export function parseNumberHeader(rawValue: string | null) {
  if (!rawValue) {
    return null;
  }

  const parsedValue = Number(rawValue);
  return Number.isFinite(parsedValue) ? parsedValue : null;
}

export function parseBooleanHeader(rawValue: string | null) {
  return rawValue === "true";
}
