import { NextResponse } from 'next/server';
import { withErrorHandler, RouteContext } from '@server/middleware/withErrorHandler';
import { withAuth, AuthedRequest } from '@server/middleware/withAuth';
import { withValidationAuthed } from '@server/middleware/withValidation';
import { updatePhoneNumberSchema } from '@server/validators/phone-numbers.validator';
import { getPhoneNumber, updatePhoneNumber, deletePhoneNumber } from '@server/services/phone-numbers.service';
import { requirePlanFeature } from '@server/utils/features';

export const GET = withErrorHandler(
  withAuth(async (req: AuthedRequest, ctx: RouteContext) => {
    await requirePlanFeature(req.session.restaurantId!, 'voice_agent');
    const { id } = await ctx.params;
    const number = await getPhoneNumber(id, req.session.restaurantId!);
    return NextResponse.json({ number });
  })
);

export const PATCH = withErrorHandler(
  withAuth(
    withValidationAuthed(updatePhoneNumberSchema, async (req, ctx: RouteContext) => {
      await requirePlanFeature(req.session.restaurantId!, 'voice_agent');
      const { id } = await ctx.params;
      const number = await updatePhoneNumber(id, req.session.restaurantId!, req.parsedBody as Record<string, unknown>);
      return NextResponse.json({ number });
    })
  )
);

export const DELETE = withErrorHandler(
  withAuth(async (req: AuthedRequest, ctx: RouteContext) => {
    await requirePlanFeature(req.session.restaurantId!, 'voice_agent');
    const { id } = await ctx.params;
    await deletePhoneNumber(id, req.session.restaurantId!);
    return NextResponse.json({ success: true });
  })
);
