import {
  getActiveStreak,
  resetStreak,
  updateStreakSavings,
} from "../../db/streak";

/** PATCH /api/streak – reset oder avg_monthly_savings aktualisieren */
export default defineEventHandler(async (event) => {
  const user = await requireUser(event);
  const body = await readBody(event);

  const current = await getActiveStreak(user.id);
  if (!current)
    throw createError({ statusCode: 404, message: "Kein aktiver Streak" });

  if (body.reset === true) {
    const longest = Math.max(current.longestDays, current.currentDays);
    const reason = body.reason ?? "manual";
    return resetStreak(current.id, longest, user.id, reason);
  }

  if (body.avgMonthlySavings !== undefined) {
    return updateStreakSavings(current.id, body.avgMonthlySavings);
  }

  return current;
});
