import { NextRequest, NextResponse } from "next/server" import { getServerSession } from "next-auth" import { authOptions } from "@/lib/auth" import { prisma } from "@/lib/prisma" import type { DailyLog } from "@prisma/client" // GET - Obtener estadísticas de los logs export async function GET(req: NextRequest) { try { const session = await getServerSession(authOptions) if (!session?.user) { return NextResponse.json({ error: "No autorizado" }, { status: 401 }) } if (session.user.role !== "PATIENT") { return NextResponse.json( { error: "Solo pacientes pueden acceder a estadísticas" }, { status: 403 } ) } // Obtener parámetros const searchParams = req.nextUrl.searchParams const startDate = searchParams.get("startDate") const endDate = searchParams.get("endDate") // Si no hay fechas, usar últimos 30 días const end = endDate ? new Date(endDate) : new Date() const start = startDate ? new Date(startDate) : new Date(end.getTime() - 30 * 24 * 60 * 60 * 1000) // Obtener logs en el rango const logs = await prisma.dailyLog.findMany({ where: { userId: session.user.id, date: { gte: start, lte: end, }, }, orderBy: { date: "asc", }, }) // Calcular estadísticas const totalEntries = logs.length if (totalEntries === 0) { return NextResponse.json({ totalEntries: 0, avgMood: null, avgEnergy: null, avgSleep: null, avgSleepQuality: null, streak: 0, moodDistribution: {}, energyDistribution: {}, }) } // Promedios const moodLogs = logs.filter((log): log is DailyLog & { mood: number } => log.mood !== null) const energyLogs = logs.filter((log): log is DailyLog & { energy: number } => log.energy !== null) const sleepLogs = logs.filter((log): log is DailyLog & { sleepHours: number } => log.sleepHours !== null) const sleepQualityLogs = logs.filter((log): log is DailyLog & { sleepQuality: number } => log.sleepQuality !== null) const avgMood = moodLogs.length ? moodLogs.reduce((sum: number, log) => sum + log.mood, 0) / moodLogs.length : null const avgEnergy = energyLogs.length ? energyLogs.reduce((sum: number, log) => sum + log.energy, 0) / energyLogs.length : null const avgSleep = sleepLogs.length ? sleepLogs.reduce((sum: number, log) => sum + log.sleepHours, 0) / sleepLogs.length : null const avgSleepQuality = sleepQualityLogs.length ? sleepQualityLogs.reduce((sum: number, log) => sum + log.sleepQuality, 0) / sleepQualityLogs.length : null // Calcular racha (días consecutivos con registro) let streak = 0 const today = new Date() today.setHours(0, 0, 0, 0) // Ordenar logs por fecha descendente const sortedLogs = [...logs].sort( (a, b) => new Date(b.date).getTime() - new Date(a.date).getTime() ) // Verificar si hay registro hoy o ayer const latestLog = sortedLogs[0] if (latestLog) { const latestDate = new Date(latestLog.date) latestDate.setHours(0, 0, 0, 0) const daysDiff = Math.floor( (today.getTime() - latestDate.getTime()) / (1000 * 60 * 60 * 24) ) if (daysDiff <= 1) { // Hay registro hoy o ayer, calcular racha streak = 1 const checkDate = new Date(latestDate) for (let i = 1; i < sortedLogs.length; i++) { checkDate.setDate(checkDate.getDate() - 1) const currentLogDate = new Date(sortedLogs[i].date) currentLogDate.setHours(0, 0, 0, 0) if (currentLogDate.getTime() === checkDate.getTime()) { streak++ } else { break } } } } // Distribución de mood y energy const moodDistribution: Record = {} const energyDistribution: Record = {} logs.forEach((log) => { if (log.mood) { moodDistribution[log.mood] = (moodDistribution[log.mood] || 0) + 1 } if (log.energy) { energyDistribution[log.energy] = (energyDistribution[log.energy] || 0) + 1 } }) return NextResponse.json({ totalEntries, avgMood: avgMood ? Number(avgMood.toFixed(1)) : null, avgEnergy: avgEnergy ? Number(avgEnergy.toFixed(1)) : null, avgSleep: avgSleep ? Number(avgSleep.toFixed(1)) : null, avgSleepQuality: avgSleepQuality ? Number(avgSleepQuality.toFixed(1)) : null, streak, moodDistribution, energyDistribution, }) } catch (error) { console.error("Error al calcular estadísticas:", error) return NextResponse.json( { error: "Error al calcular estadísticas" }, { status: 500 } ) } }