import { NextRequest, NextResponse } from 'next/server';
import pool from '@/lib/db';
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_id } = body;

    if (!lead_id) {
      return NextResponse.json({ error: 'lead_id is required' }, { status: 400 });
    }

    // Fetch lead from DB
    const leadResult = await pool.query('SELECT * FROM seller_leads WHERE id = $1', [lead_id]);
    if (leadResult.rows.length === 0) {
      return NextResponse.json({ error: 'Lead not found' }, { status: 404 });
    }

    // Fetch all active buyers from DB
    const buyersResult = await pool.query(
      "SELECT * FROM buyers WHERE status IN ('active', 'high-intent')"
    );

    const lead = leadResult.rows[0] as SellerLead;
    const buyers = buyersResult.rows as Buyer[];

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

    // Upsert matches into DB
    let newMatches = 0;
    for (const m of matchResults) {
      const upsert = await pool.query(
        `INSERT INTO matches (lead_id, buyer_id, match_score, status)
         VALUES ($1, $2, $3, 'pending')
         ON CONFLICT (lead_id, buyer_id) DO UPDATE SET match_score = $3
         RETURNING id`,
        [lead_id, m.buyer.id, m.score]
      );
      if (upsert.rows.length > 0) newMatches++;
    }

    return NextResponse.json({
      success: true,
      lead_id,
      total_buyers: buyers.length,
      matches_found: matchResults.length,
      new_matches: newMatches,
      matches: matchResults.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 run error:', error);
    return NextResponse.json({ error: 'Failed to run matching' }, { status: 500 });
  }
}
