import { NextResponse } from 'next/server';
import { withErrorHandler, RouteContext } from '@server/middleware/withErrorHandler';
import { withAuth, requireSection, AuthedRequest } from '@server/middleware/withAuth';
import { transferCall } from '@server/services/telephone/twilio-phone.service';
import { ValidationError } from '@server/errors';
import { requirePlanFeature } from '@server/utils/features';

export const POST = withErrorHandler(
  withAuth(async (req: AuthedRequest, ctx: RouteContext) => {
    await requireSection(req, 'telephone', 'update');
    await requirePlanFeature(req.session.restaurantId!, 'voice_agent');
    const { id } = await ctx.params;
    let body: { target_number?: string } = {};
    try {
      body = await req.json();
    } catch {
      throw new ValidationError('Invalid request body');
    }

    if (!body.target_number?.trim()) {
      throw new ValidationError('target_number is required');
    }

    await transferCall(id, req.session.restaurantId!, body.target_number.trim());
    return NextResponse.json({ success: true });
  })
);
