import { NextResponse } from "next/server";
import { requireAdminApiUser } from "@/lib/auth/admin";
import { prisma } from "@/lib/prisma";
import { getEscalationForCase } from "@/lib/legal/server";

type RouteContext = {
  params: Promise<{ caseId: string }>;
};

const VALID_STEP_KEYS = new Set([
  "formal_requirement",
  "administrative_conciliation",
  "oic_complaint",
  "sfp_or_state_challenge",
  "jurisdictional_path",
]);

function parseJsonBody(body: unknown) {
  return typeof body === "object" && body !== null ? (body as Record<string, unknown>) : {};
}

export async function GET(_request: Request, context: RouteContext) {
  const user = await requireAdminApiUser();

  if (!user) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  const { caseId } = await context.params;
  const escalation = await getEscalationForCase(user.id, caseId);

  if (!escalation) {
    return NextResponse.json({ error: "Caso no encontrado." }, { status: 404 });
  }

  return NextResponse.json({ ok: true, escalation });
}

export async function POST(request: Request, context: RouteContext) {
  const user = await requireAdminApiUser();

  if (!user) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  const { caseId } = await context.params;
  const body = parseJsonBody(await request.json().catch(() => ({})));

  const routeStepKey = typeof body.routeStepKey === "string" ? body.routeStepKey.trim() : "";
  const notes = typeof body.notes === "string" ? body.notes.trim() : "";
  const completed = body.completed === false ? false : true;

  if (!VALID_STEP_KEYS.has(routeStepKey)) {
    return NextResponse.json({ error: "routeStepKey invalido." }, { status: 400 });
  }

  const legalCase = await prisma.legalCase.findFirst({
    where: {
      id: caseId,
      userId: user.id,
    },
    select: { id: true },
  });

  if (!legalCase) {
    return NextResponse.json({ error: "Caso no encontrado." }, { status: 404 });
  }

  await prisma.legalEscalationStepLog.upsert({
    where: {
      legalCaseId_routeStepKey: {
        legalCaseId: caseId,
        routeStepKey,
      },
    },
    update: {
      completedAt: completed ? new Date() : null,
      notes,
    },
    create: {
      legalCaseId: caseId,
      routeStepKey,
      completedAt: completed ? new Date() : null,
      notes,
    },
  });

  const escalation = await getEscalationForCase(user.id, caseId);
  return NextResponse.json({ ok: true, escalation });
}
