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

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(),
});

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