import { NextRequest, NextResponse } from "next/server"; import { z } from "zod"; import { prisma } from "@/lib/db"; import { getOwnedPhase, getOwnedPlan, toPlanInput } from "@/lib/queries"; import { getCurrentUserId } from "@/lib/session"; import { maxPhaseDuration } from "@/lib/calculations"; const updatePhaseSchema = z.object({ name: z.string().min(1).max(120).optional(), durationYears: z.number().int().min(1).max(80).optional(), }); export async function PUT( request: NextRequest, { params }: { params: Promise<{ phaseId: string }> } ) { const userId = await getCurrentUserId(); if (!userId) return NextResponse.json({ error: "Nicht authentifiziert." }, { status: 401 }); const { phaseId } = await params; const existing = await getOwnedPhase(phaseId, userId); if (!existing) return NextResponse.json({ error: "Phase nicht gefunden." }, { status: 404 }); const body = await request.json(); const parsed = updatePhaseSchema.safeParse(body); if (!parsed.success) return NextResponse.json({ error: "Ungueltige Eingabe." }, { status: 400 }); let duration = parsed.data.durationYears; if (duration != null) { // Dauer ans naechste Pensionsereignis kappen (Jahre vor dieser Phase). const plan = await getOwnedPlan(existing.planId, userId); if (plan) { const planInput = toPlanInput(plan); const yearsBefore = planInput.phases .filter((p) => p.sequenceNumber < existing.sequenceNumber) .reduce((s, p) => s + p.durationYears, 0); const cap = maxPhaseDuration(planInput.persons, yearsBefore); if (cap != null) duration = Math.min(duration, cap); duration = Math.max(1, duration); } } const phase = await prisma.phase.update({ where: { id: phaseId }, data: { name: parsed.data.name ?? undefined, durationYears: duration ?? undefined, }, }); return NextResponse.json({ phase: { id: phase.id } }); } // Nur die letzte Phase kann geloescht werden (Verkettung bleibt intakt). export async function DELETE( _request: NextRequest, { params }: { params: Promise<{ phaseId: string }> } ) { const userId = await getCurrentUserId(); if (!userId) return NextResponse.json({ error: "Nicht authentifiziert." }, { status: 401 }); const { phaseId } = await params; const phase = await getOwnedPhase(phaseId, userId); if (!phase) return NextResponse.json({ error: "Phase nicht gefunden." }, { status: 404 }); const later = await prisma.phase.findFirst({ where: { planId: phase.planId, sequenceNumber: { gt: phase.sequenceNumber } }, }); if (later) { return NextResponse.json({ error: "Nur die letzte Phase kann geloescht werden." }, { status: 400 }); } await prisma.phase.delete({ where: { id: phaseId } }); return NextResponse.json({ ok: true }); }