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

export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url);
    const status = searchParams.get('status');
    const search = searchParams.get('search');

    let query = `
      SELECT m.*,
        json_build_object(
          'id', sl.id, 'address', sl.address, 'asset_type', sl.asset_type,
          'asking_price', sl.asking_price, 'cap_rate', sl.cap_rate, 'noi', sl.noi,
          'sqft', sl.sqft, 'units', sl.units, 'year_built', sl.year_built,
          'market', sl.market, 'city', sl.city, 'state', sl.state,
          'notes', sl.notes, 'status', sl.status,
          'created_at', sl.created_at, 'updated_at', sl.updated_at
        ) as seller_lead,
        json_build_object(
          'id', b.id, 'name', b.name, 'company', b.company,
          'email', b.email, 'phone', b.phone,
          'asset_types', b.asset_types, 'target_locations', b.target_locations,
          'price_min', b.price_min, 'price_max', b.price_max,
          'cap_rate_min', b.cap_rate_min, 'cap_rate_max', b.cap_rate_max,
          'preferences', b.preferences, 'status', b.status,
          'engagement_score', b.engagement_score
        ) as buyer
      FROM matches m
      JOIN seller_leads sl ON m.lead_id = sl.id
      JOIN buyers b ON m.buyer_id = b.id
      WHERE 1=1
    `;
    const params: unknown[] = [];
    let paramIndex = 1;

    if (status && status !== 'all') {
      query += ` AND m.status = $${paramIndex++}`;
      params.push(status);
    }
    if (search) {
      query += ` AND (sl.address ILIKE $${paramIndex} OR b.name ILIKE $${paramIndex})`;
      params.push(`%${search}%`);
      paramIndex++;
    }

    query += ' ORDER BY m.match_score DESC, m.created_at DESC';

    const result = await pool.query(query, params);
    return NextResponse.json(result.rows);
  } catch (error) {
    console.error('Matches GET error:', error);
    return NextResponse.json({ error: 'Failed to fetch matches' }, { status: 500 });
  }
}
