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

export const POST = withErrorHandler(
  withAuth(async (req: AuthedRequest, ctx: RouteContext) => {
    await requireSection(req, 'telephone', 'create');
    await requirePlanFeature(req.session.restaurantId!, 'voice_agent');
    const { id } = await ctx.params;
    let staffNumber: string | undefined;
    try {
      const body = await req.json();
      staffNumber = body.staff_number || undefined;
    } catch { /* no body is fine */ }
    const result = await createConference(id, req.session.restaurantId!, staffNumber);
    return NextResponse.json({ success: true, ...result });
  })
);
