import { prisma } from "./db";

export async function linkCardToPerson(cardId: string, organizationId: string) {
  const card = await prisma.responseCard.findUnique({ where: { id: cardId } });
  if (!card || card.personId) return null;

  const firstName = card.firstName || card.name?.split(" ")[0] || "";
  const lastName = card.lastName || card.name?.split(" ").slice(1).join(" ") || "";
  const email = card.email;

  if (!firstName && !lastName && !email) return null;

  // Try email match first
  if (email) {
    const match = await prisma.person.findFirst({
      where: { organizationId, email: email.toLowerCase(), mergedIntoId: null },
    });
    if (match) {
      await prisma.responseCard.update({ where: { id: cardId }, data: { personId: match.id } });
      return match;
    }
  }

  // Try name match
  if (firstName && lastName) {
    const match = await prisma.person.findFirst({
      where: {
        organizationId,
        firstName: { equals: firstName, mode: "insensitive" },
        lastName: { equals: lastName, mode: "insensitive" },
        mergedIntoId: null,
      },
    });
    if (match) {
      await prisma.responseCard.update({ where: { id: cardId }, data: { personId: match.id } });
      return match;
    }
  }

  // Create new person
  const person = await prisma.person.create({
    data: {
      organizationId,
      firstName: firstName || "Unknown",
      lastName: lastName || "",
      email: email?.toLowerCase() || null,
      cellPhone: card.cellPhone || null,
      fieldData: (card.fieldData as object) || null,
    },
  });
  await prisma.responseCard.update({ where: { id: cardId }, data: { personId: person.id } });
  return person;
}
