import type { Prisma } from "@prisma/client";
import { NextResponse } from "next/server";
import { requireAdminApiUser } from "@/lib/auth/admin";
import { prisma } from "@/lib/prisma";
import { evaluateDiagnosis, parseDiagnosisAnswers } from "@/lib/legal/diagnosis";
import { LegalDiagnosisStartInputSchema } from "@/lib/legal/types";

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

function logContinuityHandoff(event: string, data: Record<string, unknown>) {
  console.info(
    "[continuity_handoff]",
    JSON.stringify({
      event,
      at: new Date().toISOString(),
      ...data,
    }),
  );
}

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 = LegalDiagnosisStartInputSchema.safeParse(body);

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

  const input = parsed.data;
  logContinuityHandoff("m8_to_m9_diagnosis_start_requested", {
    userId: user.id,
    requestedContractId: input.contractId ?? null,
  });

  let contractId: string | null = null;
  if (input.contractId) {
    const ownedContract = await prisma.contractRecord.findFirst({
      where: {
        id: input.contractId,
        userId: user.id,
      },
      select: {
        id: true,
      },
    });

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

    contractId = ownedContract.id;
  }

  logContinuityHandoff("m8_to_m9_diagnosis_started", {
    userId: user.id,
    persistedContractId: contractId,
  });

  const normalizedAnswers = parseDiagnosisAnswers({});
  const recommendation = evaluateDiagnosis(normalizedAnswers);
  const answersJson: Record<string, unknown> = {
    ...normalizedAnswers,
  };

  if (contractId) {
    answersJson.contractId = contractId;
  }

  const diagnosis = await prisma.legalDiagnosis.create({
    data: {
      userId: user.id,
      answersJson: answersJson as Prisma.InputJsonValue,
      recommendedRouteJson: recommendation as unknown as Prisma.InputJsonValue,
      stepIndex: 1,
      totalSteps: 4,
    },
    select: {
      id: true,
      stepIndex: true,
      totalSteps: true,
      answersJson: true,
      recommendedRouteJson: true,
    },
  });

  return NextResponse.json({
    ok: true,
    diagnosis: {
      id: diagnosis.id,
      stepIndex: diagnosis.stepIndex,
      totalSteps: diagnosis.totalSteps,
      answers: diagnosis.answersJson,
      contractId,
      recommendation: diagnosis.recommendedRouteJson,
    },
  });
}
