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

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

  try {
    const body = await request.json();
    const { phoneNumber, friendlyName } = body;

    if (!phoneNumber) {
      return NextResponse.json(
        { error: 'phoneNumber is required' },
        { status: 400 }
      );
    }

    const result = await buyPhoneNumber(phoneNumber, friendlyName);
    return NextResponse.json(result);
  } catch (err) {
    console.error('Failed to buy phone number:', err);
    const message = err instanceof Error ? err.message : 'Purchase failed';
    return NextResponse.json({ error: message }, { status: 500 });
  }
}
