import { env } from "@/lib/env";

/**
 * Thin typed fetch wrapper for the ElevenLabs (ElevenAgents) API.
 * Endpoints and payload shapes: docs/kevo-flagging/API_NOTES.md.
 *
 * No retry logic here by design — callers that need retries run inside a
 * BullMQ job and get attempts/backoff from the queue, per repo convention.
 */

export class ElevenLabsApiError extends Error {
  constructor(
    public status: number,
    public body: string,
    public path: string,
  ) {
    super(`ElevenLabs API ${status} on ${path}: ${body.slice(0, 300)}`);
    this.name = "ElevenLabsApiError";
  }
}

// Optional var — read process.env directly so the env helper doesn't log
// a fatal-looking "Missing ENV" line when the default is intended.
const baseUrl = () =>
  process.env.ELEVENLABS_BASE_URL || "https://api.elevenlabs.io";

export const elevenLabsRequest = async <T>(
  path: string,
  init: Omit<RequestInit, "body"> & { body?: unknown } = {},
): Promise<T> => {
  const apiKey = env.GetString("ELEVENLABS_API_KEY");
  if (!apiKey) throw new Error("ELEVENLABS_API_KEY is not set");

  const { body, headers, ...rest } = init;
  const res = await fetch(`${baseUrl()}${path}`, {
    ...rest,
    headers: {
      "xi-api-key": apiKey,
      ...(body !== undefined ? { "Content-Type": "application/json" } : {}),
      ...headers,
    },
    ...(body !== undefined ? { body: JSON.stringify(body) } : {}),
  });

  const text = await res.text();
  if (!res.ok) throw new ElevenLabsApiError(res.status, text, path);
  return (text ? JSON.parse(text) : undefined) as T;
};
