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

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 * FROM buyers WHERE 1=1';
    const params: unknown[] = [];
    let paramIndex = 1;

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

    query += ' ORDER BY engagement_score DESC, created_at DESC';

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

export async function POST(request: NextRequest) {
  try {
    const session = await getSessionUser();
    if (!session) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
    }

    const body = await request.json();
    const {
      name, company, email, phone,
      asset_types, target_locations,
      price_min, price_max, cap_rate_min, cap_rate_max,
      preferences
    } = body;

    if (!name || !email) {
      return NextResponse.json({ error: 'Name and email are required' }, { status: 400 });
    }

    const result = await pool.query(
      `INSERT INTO buyers (agent_id, name, company, email, phone, asset_types, target_locations, price_min, price_max, cap_rate_min, cap_rate_max, preferences)
       VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12)
       RETURNING *`,
      [session.id, name, company || null, email, phone || null,
       asset_types || '{}', target_locations || '{}',
       price_min || null, price_max || null, cap_rate_min || null, cap_rate_max || null,
       preferences || null]
    );

    return NextResponse.json(result.rows[0], { status: 201 });
  } catch (error) {
    console.error('Buyers POST error:', error);
    return NextResponse.json({ error: 'Failed to create buyer' }, { status: 500 });
  }
}
