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';

export const GET = withErrorHandler(
  withAuth(async (req: AuthedRequest) => {
    const { restaurantId, branchId } = req.session;
    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) => {
      const number = await createPhoneNumber(req.session.restaurantId!, req.parsedBody as Record<string, unknown>);
      return NextResponse.json({ number }, { status: 201 });
    })
  )
);
