import { NextRequest, NextResponse } from "next/server"; import { db, mealPlans, mealPlanEntries, recipes, userNutritionGoals, eq, and } from "@epicure/db"; import { requireSession } from "@/lib/api-auth"; type Params = { params: Promise<{ weekStart: string }> }; export async function GET(_req: NextRequest, { params }: Params) { const { session, response } = await requireSession(); if (response) return response; const { weekStart } = await params; const userId = session!.user.id; // Find the meal plan for this week const plan = await db.query.mealPlans.findFirst({ where: and(eq(mealPlans.userId, userId), eq(mealPlans.weekStart, weekStart)), }); const totals = { calories: 0, protein: 0, carbs: 0, fat: 0 }; if (plan) { // Fetch all entries with their recipes const entries = await db.query.mealPlanEntries.findMany({ where: eq(mealPlanEntries.mealPlanId, plan.id), with: { recipe: { columns: { id: true, baseServings: true, nutritionData: true, }, }, }, }); for (const entry of entries) { const recipe = entry.recipe; if (!recipe || !recipe.nutritionData?.perServing) continue; const { calories, proteinG, carbsG, fatG } = recipe.nutritionData.perServing; const servings = entry.servings ?? recipe.baseServings; totals.calories += Math.round(calories * servings); totals.protein += Math.round(proteinG * servings); totals.carbs += Math.round(carbsG * servings); totals.fat += Math.round(fatG * servings); } } // Fetch user's nutrition goals const goals = await db.query.userNutritionGoals.findFirst({ where: eq(userNutritionGoals.userId, userId), }); const goalsData = goals ? { caloriesKcal: goals.caloriesKcal, proteinG: goals.proteinG, carbsG: goals.carbsG, fatG: goals.fatG, } : null; // Calculate coverage percentages const coverage = { calories: goalsData?.caloriesKcal ? Math.round((totals.calories / goalsData.caloriesKcal) * 100) : 0, protein: goalsData?.proteinG ? Math.round((totals.protein / goalsData.proteinG) * 100) : 0, carbs: goalsData?.carbsG ? Math.round((totals.carbs / goalsData.carbsG) * 100) : 0, fat: goalsData?.fatG ? Math.round((totals.fat / goalsData.fatG) * 100) : 0, }; return NextResponse.json({ totals, goals: goalsData, coverage }); }