import { NextResponse } from "next/server";
import { requireAdminApiUser } from "@/lib/auth/admin";
import {
  AuditSimulationCreateInputSchema,
} from "@/lib/audits/types";
import { createAuditSimulationForUser, getAuditKpisForUser, listAuditSimulationsForUser } from "@/lib/audits/server";

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

export async function GET() {
  const user = await requireAdminApiUser();

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

  const [simulations, kpis] = await Promise.all([listAuditSimulationsForUser(user.id), getAuditKpisForUser(user.id)]);
  return NextResponse.json({ ok: true, simulations, kpis });
}

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

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

  const body = parseJsonBody(await request.json().catch(() => ({})));
  const parsed = AuditSimulationCreateInputSchema.safeParse(body);

  if (!parsed.success) {
    return NextResponse.json({ error: "Datos de simulacion invalidos." }, { status: 400 });
  }

  const simulation = await createAuditSimulationForUser(user.id, parsed.data);
  return NextResponse.json({ ok: true, simulation });
}
