import { NextRequest, NextResponse } from "next/server"; import { z } from "zod"; import { prisma } from "@/lib/db"; import { getOwnedScenario, toPlanInput } from "@/lib/queries"; import { getCurrentUserId } from "@/lib/session"; import { touchScenario } from "@/lib/versioning-db"; import { planHorizonChange } from "@/lib/retirement"; import { MAX_PLANNING_HORIZON_YEARS, MIN_PLANNING_HORIZON_YEARS } from "@/lib/constants"; // Planungshorizont setzen: wie viele JAHRE die Planung umfasst. // // Wie beim Pensionsalter gilt: Zahl stellen, Struktur folgt. Die LETZTE Lebensphase wird so // verlängert oder gekürzt, dass der Plan genau bis zum Horizont läuft. Gibt es noch keine // Phasen, wird nur die Zahl gespeichert -- sie ist dann die Grundlage, auf der der Assistent // die Zeitachse aufspannt. const bodySchema = z.object({ horizonYears: z.number().int().min(MIN_PLANNING_HORIZON_YEARS).max(MAX_PLANNING_HORIZON_YEARS), }); export async function POST(request: NextRequest, { params }: { params: Promise<{ scenarioId: string }> }) { const userId = await getCurrentUserId(); if (!userId) return NextResponse.json({ error: "Nicht authentifiziert." }, { status: 401 }); const { scenarioId } = await params; const scenario = await getOwnedScenario(scenarioId, userId); if (!scenario) return NextResponse.json({ error: "Szenario nicht gefunden." }, { status: 404 }); const parsed = bodySchema.safeParse(await request.json().catch(() => ({}))); if (!parsed.success) return NextResponse.json({ error: "Ungültige Eingabe." }, { status: 400 }); const { horizonYears } = parsed.data; const planInput = toPlanInput(scenario); const change = planInput.phases.length > 0 ? planHorizonChange(planInput, horizonYears) : null; if (change?.blocked) return NextResponse.json({ error: change.blocked }, { status: 400 }); await prisma.$transaction([ prisma.scenario.update({ where: { id: scenarioId }, data: { planningHorizonYears: horizonYears } }), ...(change ? [prisma.phase.update({ where: { id: change.lastPhaseId }, data: { durationYears: change.newDuration } })] : []), ]); await touchScenario(scenario.id, userId); return NextResponse.json({ ok: true, lastPhaseDuration: change?.newDuration ?? null }); }