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

// Helper to get the start of the day in UTC
function getStartOfDay(date: Date): Date {
  const d = new Date(date);
  d.setUTCHours(0, 0, 0, 0);
  return d;
}

export default defineEventHandler(async (event) => {
  console.log('[Visit API] Received request');
  const userId = getAuthenticatedUserId(event);

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

  // 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,
  }
});