import { prisma } from "./prisma";
import { sourceRegistry } from "./sources/registry";
import { WebsiteContactSource } from "./sources/website-contact";

export interface EnrichmentResult {
  email?: string;
  phone?: string;
  success: boolean;
  error?: string;
}

export async function enrichLeadWithEmail(leadId: string): Promise<EnrichmentResult> {
  const lead = await prisma.lead.findUnique({
    where: { id: leadId }
  });

  if (!lead || !lead.website) {
    return { success: false, error: "Lead or website not found" };
  }

  try {
    const contactSource = sourceRegistry.getSource("website-contact") as WebsiteContactSource;
    if (!contactSource) {
      return { success: false, error: "Website contact source not registered" };
    }

    console.log(`[Enrichment] Scoping website for lead ${leadId}: ${lead.website}`);
    
    // WebsiteContactSource returns an array of NormalizedLeads
    // We take the first one found or aggregate
    const results = await contactSource.run({ domain: lead.website });
    
    if (results.length === 0) {
      return { success: false, error: "No contact info found on website" };
    }

    const email = results.find(r => r.email)?.email || lead.email;
    const phone = results.find(r => r.phone)?.phone || lead.phone;

    // Update the lead record
    await prisma.lead.update({
      where: { id: leadId },
      data: {
        email: email || undefined,
        phone: phone || undefined,
        // Also update confidence if we found something new
        confidenceScore: email ? Math.max(lead.confidenceScore, 0.9) : lead.confidenceScore
      }
    });

    return { 
      success: true, 
      email: email || undefined, 
      phone: phone || undefined 
    };

  } catch (error: any) {
    console.error(`[Enrichment] Failed for lead ${leadId}:`, error);
    return { success: false, error: error.message };
  }
}
