import { NextResponse } from "next/server";
import { OrganizationDocumentType } from "@prisma/client";
import { getSessionPayload } from "@/lib/auth/session";
import { prisma } from "@/lib/prisma";

function normalizeString(value: unknown) {
  if (typeof value !== "string") {
    return null;
  }

  const trimmed = value.trim();
  return trimmed.length > 0 ? trimmed : null;
}

function normalizeOptionalBoolean(value: unknown) {
  if (typeof value === "boolean") {
    return value;
  }

  if (typeof value !== "string") {
    return null;
  }

  const normalized = value.trim().toLowerCase();

  if (normalized === "yes" || normalized === "si" || normalized === "true") {
    return true;
  }

  if (normalized === "no" || normalized === "false") {
    return false;
  }

  return null;
}

export async function POST(request: Request) {
  const session = await getSessionPayload();

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

  try {
    const body = (await request.json()) as Record<string, unknown>;

    const name = normalizeString(body.name);
    const tradeName = normalizeString(body.tradeName);
    const rfc = normalizeString(body.rfc);
    const legalRepresentative = normalizeString(body.legalRepresentative);
    const incorporationDate = normalizeString(body.incorporationDate);
    const deedNumber = normalizeString(body.deedNumber);
    const notaryName = normalizeString(body.notaryName);
    const fiscalAddress = normalizeString(body.fiscalAddress);
    const businessPurpose = normalizeString(body.businessPurpose);
    const industry = normalizeString(body.industry);
    const operatingState = normalizeString(body.operatingState);
    const municipality = normalizeString(body.municipality);
    const companySize = normalizeString(body.companySize);
    const yearsOfOperation = normalizeString(body.yearsOfOperation);
    const annualRevenueRange = normalizeString(body.annualRevenueRange);
    const hasGovernmentContracts = normalizeOptionalBoolean(body.hasGovernmentContracts);
    const country = normalizeString(body.country);
    const primaryObjective = normalizeString(body.primaryObjective);

    if (!name) {
      return NextResponse.json({ error: "El nombre legal de la empresa es obligatorio." }, { status: 400 });
    }

    try {
      const actaDocument = await prisma.organizationDocument.findUnique({
        where: {
          userId_type: {
            userId: session.userId,
            type: OrganizationDocumentType.ACTA_CONSTITUTIVA,
          },
        },
        select: { id: true },
      });

      if (!actaDocument) {
        return NextResponse.json({ error: "Debes cargar el Acta constitutiva antes de finalizar onboarding." }, { status: 400 });
      }

      await prisma.organization.upsert({
        where: { userId: session.userId },
        update: {
          name,
          tradeName,
          rfc,
          legalRepresentative,
          incorporationDate,
          deedNumber,
          notaryName,
          fiscalAddress,
          businessPurpose,
          industry,
          operatingState,
          municipality,
          companySize,
          yearsOfOperation,
          annualRevenueRange,
          hasGovernmentContracts,
          country,
          primaryObjective,
          onboardingCompletedAt: new Date(),
        },
        create: {
          userId: session.userId,
          name,
          tradeName,
          rfc,
          legalRepresentative,
          incorporationDate,
          deedNumber,
          notaryName,
          fiscalAddress,
          businessPurpose,
          industry,
          operatingState,
          municipality,
          companySize,
          yearsOfOperation,
          annualRevenueRange,
          hasGovernmentContracts,
          country,
          primaryObjective,
          onboardingCompletedAt: new Date(),
        },
      });
    } catch {
      // Backward compatibility for databases without onboarding v2 migration.
      await prisma.organization.upsert({
        where: { userId: session.userId },
        update: {
          name,
          industry,
          companySize,
          country,
          primaryObjective,
        },
        create: {
          userId: session.userId,
          name,
          industry,
          companySize,
          country,
          primaryObjective,
        },
      });
    }

    return NextResponse.json({ ok: true, redirectTo: "/diagnostic" });
  } catch {
    return NextResponse.json({ error: "Invalid onboarding payload." }, { status: 400 });
  }
}
