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

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

    const search = searchParams.get('search') || undefined;
    const status = searchParams.get('status') || undefined;
    const bot = searchParams.get('bot') || undefined;
    const limit = parseInt(searchParams.get('limit') || '50', 10);
    const offset = parseInt(searchParams.get('offset') || '0', 10);

    const contacts = getAllContacts({
      search,
      status,
      bot,
      limit: Math.min(limit, 200), // cap at 200
      offset: Math.max(offset, 0),
    });

    return NextResponse.json({ contacts, count: contacts.length });
  } catch (error) {
    console.error('GET /api/contacts error:', error);
    return NextResponse.json(
      { error: 'Failed to fetch contacts' },
      { status: 500 }
    );
  }
}
