import { NextResponse } from "next/server";
import { requireAdminApiUser } from "@/lib/auth/admin";
import { prisma } from "@/lib/prisma";
import { generateLegalDocument } from "@/lib/legal/ai-documents";
import { LegalDocumentGenerateInputSchema } from "@/lib/legal/types";

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

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

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

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

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

    const input = parsed.data;

    let legalCaseId: string | null = input.legalCaseId ?? null;
    if (legalCaseId) {
      const ownedCase = await prisma.legalCase.findFirst({
        where: {
          id: legalCaseId,
          userId: user.id,
        },
        select: { id: true },
      });

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

      legalCaseId = ownedCase.id;
    }

    const generated = await generateLegalDocument({
      legalCaseId,
      caseType: input.caseType,
      severity: input.severity,
      templateKey: input.templateKey ?? null,
      counterparty: input.counterparty,
      companyName: input.companyName,
      amountAtRisk: input.amountAtRisk ?? null,
      description: input.description,
      objective: input.objective,
    });

    const title = input.title?.trim() || generated.title;

    const document = await prisma.legalDocument.create({
      data: {
        legalCaseId,
        userId: user.id,
        templateKey: input.templateKey ?? null,
        aiGenerated: generated.engine === "openai_json_object",
        title,
        content: generated.content,
      },
    });

    return NextResponse.json({
      ok: true,
      document: {
        id: document.id,
        legalCaseId: document.legalCaseId,
        templateKey: document.templateKey,
        aiGenerated: document.aiGenerated,
        title: document.title,
        content: document.content,
        createdAt: document.createdAt.toISOString(),
      },
      generation: {
        engine: generated.engine,
        model: generated.model,
        warnings: generated.warnings,
        usage: generated.usage,
      },
    });
  } catch {
    return NextResponse.json({ error: "No fue posible generar el escrito legal." }, { status: 400 });
  }
}
