import { NextRequest, NextResponse } from 'next/server';
import { searchAvailableNumbers, hasTwilioCredentials } from '@/lib/twilio-client';

export async function GET(request: NextRequest) {
  if (!hasTwilioCredentials()) {
    return NextResponse.json(
      { error: 'Twilio credentials not configured' },
      { status: 400 }
    );
  }

  try {
    const { searchParams } = request.nextUrl;

    const results = await searchAvailableNumbers({
      country: searchParams.get('country') || 'US',
      areaCode: searchParams.get('areaCode') || undefined,
      contains: searchParams.get('contains') || undefined,
      smsEnabled: searchParams.get('smsEnabled') === 'true' ? true : undefined,
      voiceEnabled: searchParams.get('voiceEnabled') === 'true' ? true : undefined,
      mmsEnabled: searchParams.get('mmsEnabled') === 'true' ? true : undefined,
      type: (searchParams.get('type') as 'local' | 'tollFree') || 'local',
      limit: parseInt(searchParams.get('limit') || '20', 10),
    });

    return NextResponse.json(results);
  } catch (err) {
    console.error('Failed to search available numbers:', err);
    const message = err instanceof Error ? err.message : 'Search failed';
    return NextResponse.json({ error: message }, { status: 500 });
  }
}
