import { createUrgeLog } from "../../db/urge";
import { addStreakEvent } from "../../db/streak";

type Emotion = "stress" | "sadness" | "anger" | "empty" | "boredom" | "other";
const VALID_EMOTIONS: Emotion[] = [
  "stress",
  "sadness",
  "anger",
  "empty",
  "boredom",
  "other",
];

/** POST /api/urge */
export default defineEventHandler(async (event) => {
  const user = await requireUser(event);
  const body = await readBody(event);
  const { emotion, wasOvercome, breathingDone } = body ?? {};

  if (!VALID_EMOTIONS.includes(emotion)) {
    throw createError({ statusCode: 400, message: "Ungültige Emotion" });
  }

  const log = await createUrgeLog(
    user.id,
    emotion,
    !!wasOvercome,
    !!breathingDone,
  );

  // StreakEvent loggen
  if (wasOvercome) {
    await addStreakEvent(user.id, "milestone", {
      type: "urge_overcome",
      emotion,
    });
  } else {
    await addStreakEvent(user.id, "relapse", { emotion });
  }

  return log;
});
