import { AxiosError } from "axios";

const TEMPLATE_TENANT_ID = "adf98293-41ba-4bda-bdb4-70e30a70c1b7";

export function buildTemplateRequestHeaders(
  unitId?: string,
  extra?: Record<string, string>,
): Record<string, string> {
  const headers: Record<string, string> = {
    "x-tenant-id": TEMPLATE_TENANT_ID,
    ...extra,
  };

  if (unitId) {
    headers["x-current-unit-id"] = unitId;
  }

  return headers;
}

export function parseRecordApiError(
  error: unknown,
  options?: { arrayBufferResponse?: boolean },
): string {
  const err = error as AxiosError;
  if (!err?.response) {
    return err instanceof Error ? err.message : "Request failed";
  }

  const data = err.response.data;

  if (options?.arrayBufferResponse) {
    if (data instanceof ArrayBuffer) {
      try {
        const text = new TextDecoder().decode(data);
        const json = JSON.parse(text) as { message?: string | string[] };
        if (Array.isArray(json.message)) return json.message.join(", ");
        if (typeof json.message === "string") return json.message;
        return text || "Request failed";
      } catch {
        return "Request failed";
      }
    }
    if (typeof data === "string") {
      try {
        const json = JSON.parse(data) as { message?: string | string[] };
        if (typeof json.message === "string") return json.message;
        if (Array.isArray(json.message)) return json.message.join(", ");
      } catch {
        return data;
      }
    }
  }

  if (typeof data === "object" && data !== null && "message" in data) {
    const message = (data as { message?: string | string[] }).message;
    if (Array.isArray(message)) return message.join(", ");
    if (typeof message === "string") return message;
  }

  return err.message || "Request failed";
}
