import { NextResponse } from "next/server";

export async function POST(request: Request) {
  try {
    const apiKey = process.env.OPENAI_API_KEY;
    if (!apiKey) {
      return NextResponse.json(
        { error: "OPENAI_API_KEY manquante." },
        { status: 400 }
      );
    }

    const body = await request.formData();
    const audio = body.get("audio");
    if (!(audio instanceof File)) {
      return NextResponse.json(
        { error: "Fichier audio manquant." },
        { status: 400 }
      );
    }

    if (audio.size === 0) {
      return NextResponse.json(
        { error: "Audio vide. Reessayez l'enregistrement." },
        { status: 400 }
      );
    }

    if (audio.size > 25 * 1024 * 1024) {
      return NextResponse.json(
        { error: "Audio trop volumineux (>25MB)." },
        { status: 400 }
      );
    }

    const model = process.env.OPENAI_TRANSCRIBE_MODEL || "gpt-4o-mini-transcribe";

    const payload = new FormData();
    payload.append("model", model);
    payload.append("language", "fr");
    payload.append("file", audio, audio.name || "recording.webm");

    const response = await fetch("https://api.openai.com/v1/audio/transcriptions", {
      method: "POST",
      headers: {
        Authorization: `Bearer ${apiKey}`
      },
      body: payload
    });

    if (!response.ok) {
      const detail = await response.text();
      return NextResponse.json(
        {
          error: `Transcription OpenAI en echec (${response.status}).`,
          details: detail
        },
        { status: 400 }
      );
    }

    const result = (await response.json()) as { text?: string };
    return NextResponse.json({ text: result.text ?? "" });
  } catch (error) {
    const message =
      error instanceof Error ? error.message : "Erreur pendant la transcription.";
    return NextResponse.json({ error: message }, { status: 500 });
  }
}
