import { NextRequest, NextResponse } from "next/server"; import { z } from "zod"; import { prisma } from "@/lib/db"; import { getCurrentUserId } from "@/lib/session"; const personSchema = z.object({ role: z.enum(["PERSON_A", "PERSON_B"]), name: z.string().max(60).nullish(), age: z.number().int().min(0).max(120), retirementAge: z.number().int().min(30).max(100), }); // Das Grundprofil liegt am SZENARIO (nicht am Plan) -- dadurch kann ein Szenario z. B. ein // anderes Pensionsalter tragen als das Basisszenario (Frühpensionierungs-Szenario). export const scenarioProfileSchema = z.object({ householdType: z.enum(["SINGLE", "COUPLE"]), inflationRateDefault: z.number().min(-20).max(50), persons: z.array(personSchema).min(1).max(2), }); const createPlanSchema = z.object({ name: z.string().min(1).max(120) }).and(scenarioProfileSchema); export function validatePersonsForType(data: z.infer): string | null { if (data.householdType === "SINGLE" && data.persons.length !== 1) { return "Einzelperson-Plan benoetigt genau eine Person."; } if (data.householdType === "COUPLE" && data.persons.length !== 2) { return "Paar-Plan benoetigt genau zwei Personen (Person A und Person B)."; } return null; } // Liste der Plaene mit ihrem Szenario-Baum (nur Kopfdaten). export async function GET() { const userId = await getCurrentUserId(); if (!userId) return NextResponse.json({ error: "Nicht authentifiziert." }, { status: 401 }); const plans = await prisma.plan.findMany({ where: { userId }, orderBy: { createdAt: "asc" }, select: { id: true, name: true, createdAt: true, scenarios: { orderBy: [{ isBase: "desc" }, { createdAt: "asc" }], select: { id: true, planId: true, name: true, isBase: true, parentScenarioId: true }, }, }, }); return NextResponse.json({ plans }); } // Legt einen Plan an -- zusammen mit seinem Basisszenario, das das Grundprofil traegt. export async function POST(request: NextRequest) { const userId = await getCurrentUserId(); if (!userId) return NextResponse.json({ error: "Nicht authentifiziert." }, { status: 401 }); const body = await request.json(); const parsed = createPlanSchema.safeParse(body); if (!parsed.success) return NextResponse.json({ error: parsed.error.flatten() }, { status: 400 }); const error = validatePersonsForType(parsed.data); if (error) return NextResponse.json({ error }, { status: 400 }); const plan = await prisma.plan.create({ data: { userId, name: parsed.data.name, scenarios: { create: { name: "Basisszenario", isBase: true, householdType: parsed.data.householdType, inflationRateDefault: parsed.data.inflationRateDefault, persons: { create: parsed.data.persons }, }, }, }, include: { scenarios: true }, }); return NextResponse.json( { plan: { id: plan.id }, scenario: { id: plan.scenarios[0].id } }, { status: 201 } ); }