import { NextRequest, NextResponse } from 'next/server' import { pool, Lead } from '@/lib/db' export async function GET(request: NextRequest) { try { const { searchParams } = new URL(request.url) const page = parseInt(searchParams.get('page') || '1') const limit = parseInt(searchParams.get('limit') || '50') const sortBy = searchParams.get('sortBy') || 'created_at' const sortOrder = searchParams.get('sortOrder') || 'DESC' const search = searchParams.get('search') || '' const offset = (page - 1) * limit let whereClause = '' let queryParams: any[] = [limit, offset] if (search) { whereClause = `WHERE (first_name ILIKE $3 OR last_name ILIKE $3 OR email ILIKE $3 OR company_name ILIKE $3)` queryParams.push(`%${search}%`) } const validSortColumns = ['created_at', 'first_name', 'last_name', 'email', 'company_name', 'lead_source'] const sortColumn = validSortColumns.includes(sortBy) ? sortBy : 'created_at' const order = sortOrder.toUpperCase() === 'ASC' ? 'ASC' : 'DESC' const leadsQuery = ` SELECT * FROM leads ${whereClause} ORDER BY ${sortColumn} ${order} LIMIT $1 OFFSET $2 ` const countQuery = `SELECT COUNT(*) as total FROM leads ${whereClause}` const [leadsResult, countResult] = await Promise.all([ pool.query(leadsQuery, queryParams), pool.query(countQuery, search ? [`%${search}%`] : []) ]) const leads: Lead[] = leadsResult.rows const total = parseInt(countResult.rows[0].total) const totalPages = Math.ceil(total / limit) return NextResponse.json({ leads, pagination: { page, limit, total, totalPages, hasNext: page < totalPages, hasPrev: page > 1 } }) } catch (error) { console.error('Error fetching leads:', error) return NextResponse.json( { error: 'Failed to fetch leads' }, { status: 500 } ) } }