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 { z } from 'zod';
import { purchaseNumber } from '@server/services/telephone/twilio-phone.service';
import { requirePlanFeature } from '@server/utils/features';

const purchaseSchema = z.object({
  phone_number: z.string().min(1),
});

export const POST = withErrorHandler(
  withAuth(
    withValidationAuthed(purchaseSchema, async (req) => {
      await requireSection(req, 'telephone', 'create');
      await requirePlanFeature(req.session.restaurantId!, 'voice_agent');
      const { phone_number } = req.parsedBody as { phone_number: string };
      const result = await purchaseNumber(req.session.restaurantId!, phone_number);
      return NextResponse.json({ success: true, ...result });
    })
  )
);
