import { NextResponse } from 'next/server';
import { withErrorHandler } from '@server/middleware/withErrorHandler';
import { withAuth } from '@server/middleware/withAuth';
import { withValidationAuthed } from '@server/middleware/withValidation';
import { z } from 'zod';
import { initiateOutboundCall } from '@server/services/telephone/twilio-phone.service';

const outboundSchema = z.object({
  to: z.string().min(1),
  from_number_id: z.string().uuid(),
});

export const POST = withErrorHandler(
  withAuth(
    withValidationAuthed(outboundSchema, async (req) => {
      const { to, from_number_id } = req.parsedBody as { to: string; from_number_id: string };
      const result = await initiateOutboundCall(req.session.restaurantId!, to, from_number_id);
      return NextResponse.json({ success: true, ...result });
    })
  )
);
