import { prisma } from "@/lib/prisma";
import { NormalizedLead } from "./sources/types";

export interface DedupResult {
  isDuplicate: boolean;
  existingId?: string;
  matchScore: number;
}

/**
 * Checks if a lead already exists in the database based on several criteria.
 */
export async function checkDuplicate(lead: NormalizedLead): Promise<DedupResult> {
  // 1. Check by exact email
  if (lead.email) {
    const existingEmail = await prisma.lead.findFirst({
      where: { email: lead.email },
      select: { id: true }
    });
    if (existingEmail) return { isDuplicate: true, existingId: existingEmail.id, matchScore: 1.0 };
  }

  // 2. Check by exact website
  if (lead.website) {
    const normalizedWebsite = lead.website.replace(/^https?:\/\/(www\.)?/, "").replace(/\/$/, "");
    const existingWebsite = await prisma.lead.findFirst({
      where: {
        website: {
          contains: normalizedWebsite
        }
      },
      select: { id: true }
    });
    if (existingWebsite) return { isDuplicate: true, existingId: existingWebsite.id, matchScore: 0.95 };
  }

  // 3. Check by exact phone
  if (lead.phone) {
    const existingPhone = await prisma.lead.findFirst({
      where: { phone: lead.phone },
      select: { id: true }
    });
    if (existingPhone) return { isDuplicate: true, existingId: existingPhone.id, matchScore: 0.9 };
  }

  // 4. Fuzzy check by business name + city
  if (lead.businessName && lead.city) {
    const existingName = await prisma.lead.findFirst({
      where: {
        businessName: {
          contains: lead.businessName
        },
        city: lead.city
      },
      select: { id: true }
    });
    if (existingName) return { isDuplicate: true, existingId: existingName.id, matchScore: 0.8 };
  }

  return { isDuplicate: false, matchScore: 0 };
}
