/**
 * POST /api/coach/sos-session — Erstellt Session für SSE-Stream
 *
 * Client sendet messages + locale, Backend generiert sessionId
 * und speichert Daten in-memory. Client nutzt dann GET /api/coach/sos-stream?session=xyz
 *
 * Grund: react-native-sse (EventSource API) unterstützt nur GET, nicht POST.
 * Daher 2-Step-Flow: POST Session erstellen → GET Stream öffnen.
 */
export default defineEventHandler(async (event) => {
  const user = await requireUser(event);
  const body = await readBody(event);
  const { messages, locale, llmProvider } = body as {
    messages: Array<{ role: "user" | "assistant"; content: string }>;
    locale?: string;
    llmProvider?: string;
  };

  if (!messages || !Array.isArray(messages)) {
    throw createError({ statusCode: 400, message: "messages fehlt" });
  }

  // Session-ID generieren
  const sessionId = `sos_${user.id}_${Date.now()}_${Math.random().toString(36).slice(2, 9)}`;

  // In globalem Store speichern (siehe server/utils/sosSessions.ts)
  const { setSosSession } = await import("../../utils/sosSessions");
  setSosSession(sessionId, {
    userId: user.id,
    messages,
    locale: locale ?? "de",
    llmProvider,
    createdAt: Date.now(),
  });

  return { sessionId };
});
