import { NextResponse } from "next/server";
import { prisma } from "@/lib/db";
import { requireApiAuthWithOrg, handleApiError } from "@/lib/api-auth";
import { linkCardToPerson } from "@/lib/person-linker";

const BATCH_LIMIT = 100;

export async function POST() {
  try {
    const session = await requireApiAuthWithOrg();
    const orgId = session.user.orgId!;

    const unlinkedCards = await prisma.responseCard.findMany({
      where: {
        organizationId: orgId,
        personId: null,
        ocrStatus: "complete",
      },
      take: BATCH_LIMIT,
      select: { id: true },
    });

    let linked = 0;
    let created = 0;

    for (const card of unlinkedCards) {
      const personCountBefore = await prisma.person.count({ where: { organizationId: orgId } });
      const result = await linkCardToPerson(card.id, orgId);
      if (result) {
        const personCountAfter = await prisma.person.count({ where: { organizationId: orgId } });
        if (personCountAfter > personCountBefore) {
          created++;
        } else {
          linked++;
        }
      }
    }

    return NextResponse.json({
      linked,
      created,
      total: unlinkedCards.length,
    });
  } catch (error) {
    return handleApiError(error);
  }
}
