import { createSosSession } from "../../db/sosSession";

/** POST /api/sos/session — speichert kompletten SOS-Verlauf für DiGA-Auswertung */
export default defineEventHandler(async (event) => {
  const user = await requireUser(event);
  const body = await readBody(event);

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

  // Hard limit gegen Spam: max 200 messages, max 1MB body
  const messages = body.messages.slice(0, 200);

  const rating =
    typeof body.feedbackRating === "number"
      ? Math.max(1, Math.min(5, Math.floor(body.feedbackRating)))
      : null;

  const session = await createSosSession(user.id, {
    startedAt: body.startedAt,
    endedAt: body.endedAt ?? new Date(),
    durationSec: typeof body.durationSec === "number" ? body.durationSec : null,
    messages,
    gamesPlayed: Array.isArray(body.gamesPlayed)
      ? body.gamesPlayed.slice(0, 20)
      : [],
    breathingCount:
      typeof body.breathingCount === "number" ? body.breathingCount : 0,
    wasOvercome: !!body.wasOvercome,
    feedbackBetter:
      typeof body.feedbackBetter === "boolean" ? body.feedbackBetter : null,
    feedbackRating: rating,
    feedbackText:
      typeof body.feedbackText === "string"
        ? body.feedbackText.slice(0, 1000)
        : null,
    locale: typeof body.locale === "string" ? body.locale.slice(0, 10) : null,
  });

  return { id: session.id };
});
