import { NextResponse } from "next/server";
import { requireAdminApiUser } from "@/lib/auth/admin";
import { AuditSimulationScoreInputSchema } from "@/lib/audits/types";
import { scoreAuditSimulationForUser } from "@/lib/audits/server";

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

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

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

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

  const { id } = await context.params;
  const body = parseJsonBody(await request.json().catch(() => ({})));
  const parsed = AuditSimulationScoreInputSchema.safeParse(body);

  if (!parsed.success) {
    return NextResponse.json({ error: "Payload de scoring invalido." }, { status: 400 });
  }

  const simulation = await scoreAuditSimulationForUser(user.id, id, parsed.data);

  if (!simulation) {
    return NextResponse.json({ error: "Simulacion no encontrada." }, { status: 404 });
  }

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