/**
 * POST /api/coach/speak-deepgram
 * Deepgram Aura TTS — returns base64 MP3
 */
export default defineEventHandler(async (event) => {
  await requireUser(event);

  const body = await readBody(event);
  const { text } = body as { text: string };

  if (!text?.trim()) {
    throw createError({ statusCode: 400, message: "text fehlt" });
  }

  const config = useRuntimeConfig();
  const key = config.deepgramApiKey as string | undefined;

  if (!key) {
    throw createError({ statusCode: 503, message: "Deepgram API Key nicht konfiguriert" });
  }

  const response = await fetch(
    "https://api.deepgram.com/v1/speak?model=aura-asteria-en&encoding=mp3",
    {
      method: "POST",
      headers: {
        Authorization: `Token ${key}`,
        "Content-Type": "application/json",
      },
      body: JSON.stringify({ text: text.slice(0, 2000) }),
    },
  );

  if (!response.ok) {
    const err = await response.text();
    console.error("[speak-deepgram] error:", response.status, err);
    throw createError({ statusCode: 502, message: "Deepgram TTS fehlgeschlagen" });
  }

  const buffer = await response.arrayBuffer();
  const base64 = Buffer.from(buffer).toString("base64");

  return { audio: `data:audio/mp3;base64,${base64}` };
});
