import { NextResponse } from 'next/server';
import { withErrorHandler } from '@server/middleware/withErrorHandler';
import { withAuth, requireSection } from '@server/middleware/withAuth';
import { withValidationAuthed } from '@server/middleware/withValidation';
import { assignAgentSchema } from '@server/validators/telephone.validator';
import { assignAgentToNumber } from '@server/services/telephone/twilio-phone.service';
import { requirePlanFeature } from '@server/utils/features';

export const POST = withErrorHandler(
  withAuth(
    withValidationAuthed(assignAgentSchema, async (req) => {
      await requireSection(req, 'telephone', 'update');
      await requirePlanFeature(req.session.restaurantId!, 'voice_agent');
      const { number_id, agent_id } = req.parsedBody as { number_id: string; agent_id: string | null };
      await assignAgentToNumber(number_id, req.session.restaurantId!, agent_id);
      return NextResponse.json({ success: true });
    })
  )
);
