import { NextResponse } from "next/server"; import { auth } from "@/lib/auth"; import { prisma } from "@/lib/prisma"; import { dispatchWebhook } from "@/lib/webhooks"; export async function GET(req: Request) { const session = await auth(); if (!session?.user?.id) return NextResponse.json({ error: "Non autorisé" }, { status: 401 }); const { searchParams } = new URL(req.url); const babyId = searchParams.get("babyId"); if (!babyId) return NextResponse.json({ error: "babyId requis" }, { status: 400 }); const familyId = (session.user as { familyId?: string }).familyId; if (!familyId) return NextResponse.json({ error: "Non autorisé" }, { status: 401 }); const ownedBaby = await prisma.baby.findFirst({ where: { id: babyId, familyId } }); if (!ownedBaby) return NextResponse.json({ error: "Bébé introuvable" }, { status: 404 }); const logs = await prisma.growthLog.findMany({ where: { babyId }, orderBy: { date: "asc" }, }); return NextResponse.json(logs); } export async function POST(req: Request) { const session = await auth(); if (!session?.user?.id) return NextResponse.json({ error: "Non autorisé" }, { status: 401 }); const { babyId, date, weight, height, headCirc, notes } = await req.json(); if (!babyId || !date) { return NextResponse.json({ error: "Champs requis manquants" }, { status: 400 }); } const postFamilyId = (session.user as { familyId?: string }).familyId; if (!postFamilyId) return NextResponse.json({ error: "Non autorisé" }, { status: 401 }); const postBaby = await prisma.baby.findFirst({ where: { id: babyId, familyId: postFamilyId } }); if (!postBaby) return NextResponse.json({ error: "Bébé introuvable" }, { status: 404 }); const log = await prisma.growthLog.create({ data: { babyId, date: new Date(date), weight: weight ?? null, height: height ?? null, headCirc: headCirc ?? null, notes: notes ?? null, }, }); const familyId = (session.user as { familyId?: string }).familyId; if (familyId) { dispatchWebhook(familyId, "growth.created", { log: { id: log.id, babyId: log.babyId, date: log.date, weight: log.weight, height: log.height }, }).catch(() => {}); } return NextResponse.json(log, { status: 201 }); }