
import { NextRequest, NextResponse } from 'next/server';
import { prisma } from '@/lib/db';

// POST /api/matching/contractors - Smart contractor matching algorithm
export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const { leadId } = body;

    const lead = await prisma.lead.findUnique({
      where: { id: leadId },
    });

    if (!lead) {
      return NextResponse.json({ error: 'Lead not found' }, { status: 404 });
    }

    // Find all contractors
    const contractors = await prisma.partner.findMany({
      where: {
        isVerified: true,
        verificationStatus: 'VERIFIED',
      },
      include: {
        user: {
          select: {
            id: true,
            name: true,
            email: true,
            phone: true,
          },
        },
        performanceMetrics: {
          orderBy: {
            createdAt: 'desc',
          },
          take: 1,
        },
      },
    });

    // Calculate match scores
    const matches = await Promise.all(
      contractors.map(async (contractor: any) => {
        const score = await calculateMatchScore(lead, contractor);
        return {
          contractorId: contractor.user.id,
          contractor,
          matchScore: score.total,
          factors: score.factors,
        };
      })
    );

    // Sort by match score
    matches.sort((a, b) => b.matchScore - a.matchScore);

    // Save top 5 matches
    const topMatches = matches.slice(0, 5);
    for (const match of topMatches) {
      await prisma.contractorMatch.create({
        data: {
          leadId,
          contractorId: match.contractorId,
          matchScore: match.matchScore,
          distanceScore: match.factors.distance,
          availabilityScore: match.factors.availability,
          ratingScore: match.factors.rating,
          specialtyScore: match.factors.specialty,
          status: 'PENDING',
        },
      });
    }

    return NextResponse.json({
      success: true,
      matches: topMatches,
    });
  } catch (error) {
    console.error('Error matching contractors:', error);
    return NextResponse.json(
      { error: 'Failed to match contractors' },
      { status: 500 }
    );
  }
}

async function calculateMatchScore(lead: any, contractor: any) {
  const factors = {
    distance: 0,
    availability: 0,
    rating: 0,
    specialty: 0,
    response: 0,
  };

  // 1. Distance Score (30%)
  const serviceAreas = contractor.serviceAreas || [];
  if (serviceAreas.includes(lead.state) || serviceAreas.includes(lead.city)) {
    factors.distance = 0.30;
  }

  // 2. Availability Score (20%)
  // Check calendar for availability
  factors.availability = 0.20; // Placeholder

  // 3. Rating Score (25%)
  const latestMetrics = contractor.performanceMetrics[0];
  if (latestMetrics) {
    const rating = latestMetrics.averageRating || 0;
    factors.rating = (rating / 5) * 0.25;
  }

  // 4. Specialty Score (20%)
  const contractorServices = contractor.services || [];
  const matchingServices = lead.services.filter((s: string) =>
    contractorServices.includes(s)
  );
  factors.specialty = (matchingServices.length / lead.services.length) * 0.20;

  // 5. Response Time Score (5%)
  factors.response = 0.05; // Placeholder

  const total = Object.values(factors).reduce((sum, val) => sum + val, 0);

  return {
    total,
    factors,
  };
}
