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

export const POST = withErrorHandler(
  withAuth(async (req: AuthedRequest, ctx: RouteContext) => {
    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 });
  })
);
