import { NextResponse } from 'next/server';
import { withErrorHandler } from '@server/middleware/withErrorHandler';
import { withAuth, AuthedRequest } from '@server/middleware/withAuth';
import { withValidationAuthed } from '@server/middleware/withValidation';
import { createPhoneNumberSchema } from '@server/validators/phone-numbers.validator';
import { listPhoneNumbers, createPhoneNumber } from '@server/services/phone-numbers.service';
import { requirePlanFeature } from '@server/utils/features';

export const GET = withErrorHandler(
  withAuth(async (req: AuthedRequest) => {
    const { restaurantId, branchId } = req.session;
    await requirePlanFeature(restaurantId!, 'voice_agent');
    const url = new URL(req.url);
    const bId = url.searchParams.get('branch_id') ?? branchId ?? undefined;
    const numbers = await listPhoneNumbers(restaurantId!, bId);
    return NextResponse.json({ numbers });
  })
);

export const POST = withErrorHandler(
  withAuth(
    withValidationAuthed(createPhoneNumberSchema, async (req) => {
      await requirePlanFeature(req.session.restaurantId!, 'voice_agent');
      const number = await createPhoneNumber(req.session.restaurantId!, req.parsedBody as Record<string, unknown>);
      return NextResponse.json({ number }, { status: 201 });
    })
  )
);
