import { NextResponse } from "next/server";
import { requireAdminApiUser } from "@/lib/auth/admin";
import { prisma } from "@/lib/prisma";
import { MAX_CONTRACT_PDF_BYTES, storeContractDocumentFile } from "@/lib/contracts/storage";

export const runtime = "nodejs";

function isPdfFile(file: File) {
  return file.type === "application/pdf" || file.name.toLowerCase().endsWith(".pdf");
}

function parseKind(value: FormDataEntryValue | null) {
  const asString = typeof value === "string" ? value.trim().toUpperCase() : "";

  if (
    asString === "SIGNED_CONTRACT" ||
    asString === "ADDENDUM" ||
    asString === "DELIVERABLE_EVIDENCE" ||
    asString === "PAYMENT_EVIDENCE" ||
    asString === "OTHER"
  ) {
    return asString;
  }

  return "SIGNED_CONTRACT";
}

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

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

  const formData = await request.formData();
  const contractIdValue = formData.get("contractId");
  const fileValue = formData.get("file");

  if (!(fileValue instanceof File)) {
    return NextResponse.json({ error: "Debes adjuntar un archivo." }, { status: 400 });
  }

  if (fileValue.size <= 0) {
    return NextResponse.json({ error: "El archivo esta vacio." }, { status: 400 });
  }

  if (fileValue.size > MAX_CONTRACT_PDF_BYTES) {
    return NextResponse.json({ error: "El archivo excede el limite de 20MB." }, { status: 400 });
  }

  if (!isPdfFile(fileValue)) {
    return NextResponse.json({ error: "Solo se permiten archivos PDF para este flujo." }, { status: 400 });
  }

  const contractId = typeof contractIdValue === "string" ? contractIdValue.trim() : "";

  if (!contractId) {
    return NextResponse.json({ error: "contractId es requerido." }, { status: 400 });
  }

  const contract = await prisma.contractRecord.findFirst({
    where: {
      id: contractId,
      userId: user.id,
    },
    select: { id: true },
  });

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

  const fileBuffer = Buffer.from(await fileValue.arrayBuffer());
  const stored = await storeContractDocumentFile(user.id, contractId, fileValue.name, fileValue.type, fileBuffer);
  const kind = parseKind(formData.get("kind"));

  const document = await prisma.contractDocument.create({
    data: {
      contractId,
      fileName: stored.fileName,
      filePath: stored.filePath,
      mimeType: stored.mimeType,
      sizeBytes: stored.sizeBytes,
      checksumSha256: stored.checksumSha256,
      kind,
    },
  });

  return NextResponse.json({
    ok: true,
    document: {
      id: document.id,
      contractId: document.contractId,
      fileName: document.fileName,
      filePath: document.filePath,
      mimeType: document.mimeType,
      sizeBytes: document.sizeBytes,
      checksumSha256: document.checksumSha256,
      kind: document.kind,
      createdAt: document.createdAt.toISOString(),
    },
  });
}
