import { NextRequest, NextResponse } from "next/server";
import { matchLeadToBuyers } from "@/lib/matching";
import type { SellerLead, Buyer } from "@/types";

export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const { lead, buyers } = body as { lead: SellerLead; buyers: Buyer[] };

    if (!lead) {
      return NextResponse.json(
        { error: "Seller lead data is required" },
        { status: 400 }
      );
    }

    if (!buyers || buyers.length === 0) {
      return NextResponse.json(
        { error: "Buyer list is required" },
        { status: 400 }
      );
    }

    // Run matching algorithm
    const matches = matchLeadToBuyers(lead, buyers);

    // In production, save matches to database:
    // for (const match of matches) {
    //   await supabaseAdmin.from('matches').upsert({
    //     lead_id: lead.id,
    //     buyer_id: match.buyer.id,
    //     match_score: match.score,
    //     status: 'pending',
    //   });
    // }

    return NextResponse.json({
      success: true,
      lead_id: lead.id,
      total_buyers: buyers.length,
      matches_found: matches.length,
      matches: matches.map((m) => ({
        buyer_id: m.buyer.id,
        buyer_name: m.buyer.name,
        buyer_company: m.buyer.company,
        score: m.score,
        breakdown: m.breakdown,
      })),
    });
  } catch (error) {
    console.error("Match API error:", error);
    return NextResponse.json(
      { error: "Failed to run matching algorithm" },
      { status: 500 }
    );
  }
}

// GET: Match a specific lead against all buyers (demo mode with mock data)
export async function GET(request: NextRequest) {
  const { searchParams } = new URL(request.url);
  const leadId = searchParams.get("lead_id");

  // In production, fetch from database
  // For demo, return sample match results
  return NextResponse.json({
    success: true,
    message: "Use POST with lead and buyers data to run matching",
    example: {
      method: "POST",
      body: {
        lead: {
          id: "lead-1",
          asset_type: "Office",
          market: "New York, NY",
          asking_price: 12500000,
          cap_rate: 6.25,
        },
        buyers: [
          {
            id: "buyer-1",
            name: "Example Buyer",
            asset_types: ["Office"],
            target_locations: ["New York, NY"],
            price_min: 5000000,
            price_max: 20000000,
            cap_rate_min: 5.0,
            cap_rate_max: 8.0,
            status: "active",
          },
        ],
      },
    },
  });
}
