import { getAuthenticatedUserId } from '../../utils/auth';
import prisma from '../../utils/prisma';
import { calculateDailyStreak } from '../../utils/streak';

export default defineEventHandler(async (event) => {
  const userId = getAuthenticatedUserId(event);
  const body = await readBody(event);
  const gameDay: string = body.gameDay; // Expecting "YYYY-MM-DD"

  if (!gameDay || !/^\d{4}-\d{2}-\d{2}$/.test(gameDay)) {
    throw createError({ statusCode: 400, statusMessage: 'Invalid or missing gameDay property in request body. Expected YYYY-MM-DD.' });
  }

  // Calculate the streak and create today's visit record
  const updatedUser = await calculateDailyStreak(prisma, userId, gameDay);

  // The consumer of this endpoint needs the most up-to-date user info,
  // including the newly calculated streak.
  return {
    id: updatedUser.id,
    email: updatedUser.email,
    nickname: updatedUser.nickname,
    avatar: updatedUser.avatar,
    coins: updatedUser.coins,
    exp: updatedUser.exp,
    dailyStreak: updatedUser.dailyStreak,
    soundOn: updatedUser.soundOn,
    confettiOn: updatedUser.confettiOn,
    createdAt: updatedUser.createdAt,
    updatedAt: updatedUser.updatedAt,
  }
});