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

const updateSettingsSchema = z.object({
  number_id: z.string().uuid(),
  call_recording: z.boolean().optional(),
  call_transcription: z.boolean().optional(),
  fallback_number: z.string().max(50).nullable().optional(),
  branch_id: z.string().uuid().nullable().optional(),
  branch_routing_mode: z.enum(['assigned', 'ask_caller', 'geo_detect']).optional(),
});

export const PATCH = withErrorHandler(
  withAuth(
    withValidationAuthed(updateSettingsSchema, async (req) => {
      await requireSection(req, 'telephone', 'update');
      await requirePlanFeature(req.session.restaurantId!, 'voice_agent');
      const { number_id, ...data } = req.parsedBody as {
        number_id: string;
        call_recording?: boolean;
        call_transcription?: boolean;
        fallback_number?: string | null;
        branch_id?: string | null;
        branch_routing_mode?: 'assigned' | 'ask_caller' | 'geo_detect';
      };
      await updatePhoneNumberSettings(number_id, req.session.restaurantId!, data);
      const numbers = await listPhoneNumbers(req.session.restaurantId!);
      return NextResponse.json({ success: true, numbers });
    })
  )
);
