import { headers } from "next/headers"; import { auth } from "@/lib/auth/server"; import { db, mealPlans, eq, and } from "@epicure/db"; import { PrintTrigger } from "@/components/recipe/print-trigger"; import { getMessages, formatMessage } from "@/lib/i18n/server"; const DAYS = ["mon", "tue", "wed", "thu", "fri", "sat", "sun"] as const; const MEAL_ORDER = ["breakfast", "lunch", "dinner", "snack"] as const; function getMonday(dateStr?: string): Date { // Parse y/m/d directly into local time — new Date("YYYY-MM-DD") parses as // UTC midnight, which getDay() (local time) can read as the wrong weekday // depending on the server's timezone offset. const d = dateStr ? (() => { const [y, m, day] = dateStr.split("-").map(Number); return new Date(y!, m! - 1, day!); })() : new Date(); const dow = d.getDay(); const diff = dow === 0 ? -6 : 1 - dow; d.setDate(d.getDate() + diff); d.setHours(0, 0, 0, 0); return d; } function toDateStr(d: Date): string { const y = d.getFullYear(); const m = String(d.getMonth() + 1).padStart(2, "0"); const day = String(d.getDate()).padStart(2, "0"); return `${y}-${m}-${day}`; } export default async function MealPlanPrintPage({ searchParams, }: { searchParams: Promise<{ week?: string }>; }) { const { week } = await searchParams; const session = await auth.api.getSession({ headers: await headers() }); if (!session) return null; const m = getMessages((session.user as { locale?: string }).locale); const monday = getMonday(week); const weekStart = toDateStr(monday); const sunday = new Date(monday); sunday.setDate(sunday.getDate() + 6); const plan = await db.query.mealPlans.findFirst({ where: and(eq(mealPlans.userId, session.user.id), eq(mealPlans.weekStart, weekStart)), with: { entries: { with: { recipe: true } } }, }); const label = `${monday.toLocaleDateString("en-US", { month: "short", day: "numeric" })} – ${sunday.toLocaleDateString("en-US", { month: "short", day: "numeric", year: "numeric" })}`; const entries = plan?.entries ?? []; return ( <>

{m.mealPlan.title}

{label}

{MEAL_ORDER.map((meal) => ( ))} {DAYS.map((day) => ( {MEAL_ORDER.map((mealType) => { const entry = entries.find((e) => e.day === day && e.mealType === mealType); return ( ); })} ))}
{m.print.day}{m.mealPlan.meals[meal]}
{m.print.days[day]} {entry ? ( <> {entry.recipe?.title ?? entry.note ?? "—"} {entry.servings && ( {formatMessage(m.print.srv, { count: entry.servings })} )} ) : ( )}
); }