import { NextResponse } from 'next/server';
import { withErrorHandler } from '@server/middleware/withErrorHandler';
import { withAuth, AuthedRequest } from '@server/middleware/withAuth';
import { getTelephoneSettings, searchAvailableNumbers } from '@server/services/telephone/twilio-phone.service';
import { decrypt } from '@server/utils/crypto';
import { ValidationError } from '@server/errors';

export const GET = withErrorHandler(
  withAuth(async (req: AuthedRequest) => {
    const settings = await getTelephoneSettings(req.session.restaurantId!);
    if (!settings.twilio_connected || !settings.twilio_account_sid || !settings.twilio_auth_token) {
      throw new ValidationError('Twilio not connected');
    }

    const accountSid = decrypt(settings.twilio_account_sid);
    const authToken = decrypt(settings.twilio_auth_token);

    const url = new URL(req.url);
    const country = url.searchParams.get('country') || 'US';
    const areaCode = url.searchParams.get('areaCode') || undefined;
    const type = url.searchParams.get('type') || 'local';
    const limit = parseInt(url.searchParams.get('limit') || '20', 10);

    const result = await searchAvailableNumbers(accountSid, authToken, country, { areaCode, type, limit });
    return NextResponse.json(result);
  })
);
