import { NextResponse } from "next/server";
import { prisma } from "@/lib/db";
import { loadCase, payloadFromRow, profileIndex, serializeCase, syncCustomerFromProfile } from "@/lib/mortgage/caseService";
import { mergeProfile } from "@/lib/mortgage/extract";
import { computeProcess } from "@/lib/mortgage/gates";

export async function GET(req: Request) {
  const url = new URL(req.url);
  const id = url.searchParams.get("id");
  if (!id) return NextResponse.json({ error: "id required" }, { status: 400 });
  const row = await loadCase(id);
  if (!row) return NextResponse.json({ error: "not found" }, { status: 404 });
  return NextResponse.json(serializeCase(row));
}

export async function PATCH(req: Request) {
  const body = await req.json();
  const caseId = body.caseId as string;
  const row = await loadCase(caseId);
  if (!row) return NextResponse.json({ error: "not found" }, { status: 404 });
  const merged = mergeProfile(payloadFromRow(row.profile), body.patch || {});
  const process = computeProcess(merged, row.stopPath);
  await prisma.$transaction([
    prisma.verticalProfile.update({
      where: { caseId },
      data: profileIndex(merged),
    }),
    prisma.insuranceCase.update({
      where: { id: caseId },
      data: { processStep: process.step },
    }),
    prisma.customer.update({
      where: { id: row.customerId },
      data: syncCustomerFromProfile(merged),
    }),
  ]);
  const next = await loadCase(caseId);
  return NextResponse.json(serializeCase(next!));
}
