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

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

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

    const updates: { friendlyName?: string; smsUrl?: string; voiceUrl?: string } = {};
    if (friendlyName !== undefined) updates.friendlyName = friendlyName;
    if (smsUrl !== undefined) updates.smsUrl = smsUrl;
    if (voiceUrl !== undefined) updates.voiceUrl = voiceUrl;

    const result = await updatePhoneNumber(params.sid, updates);
    return NextResponse.json(result);
  } catch (err) {
    console.error('Failed to update phone number:', err);
    const message = err instanceof Error ? err.message : 'Update failed';
    return NextResponse.json({ error: message }, { status: 500 });
  }
}

export async function DELETE(
  _request: NextRequest,
  { params }: { params: { sid: string } }
) {
  if (!hasTwilioCredentials()) {
    return NextResponse.json(
      { error: 'Twilio credentials not configured' },
      { status: 400 }
    );
  }

  try {
    await releasePhoneNumber(params.sid);
    return NextResponse.json({ success: true });
  } catch (err) {
    console.error('Failed to release phone number:', err);
    const message = err instanceof Error ? err.message : 'Release failed';
    return NextResponse.json({ error: message }, { status: 500 });
  }
}
