import { NextResponse } from 'next/server';
import { withV1ErrorHandler } from '@server/middleware/v1Errors';
import { withApiKey, ApiKeyRequest } from '@server/middleware/withApiKey';
import { withV1Validation } from '@server/middleware/v1Validation';
import { ParsedRequest } from '@server/middleware/withValidation';
import { RouteContext } from '@server/middleware/withErrorHandler';
import { updateBookingSchema, UpdateBookingInput } from '@server/validators/bookings.validator';
import { cancelBooking, updateBooking } from '@server/services/bookings.service';

export const PATCH = withV1ErrorHandler(
  withApiKey(
    withV1Validation(updateBookingSchema, async (req: ParsedRequest<UpdateBookingInput>, ctx: RouteContext) => {
      const apiReq = req as ParsedRequest<UpdateBookingInput> & ApiKeyRequest;
      const { id } = await ctx.params;
      const updated = await updateBooking(
        id,
        apiReq.apiKey.restaurantId,
        req.parsedBody as unknown as Record<string, unknown>,
      );
      return NextResponse.json({ data: updated });
    }),
    { permission: 'bookings:write' }
  )
);

export const DELETE = withV1ErrorHandler(
  withApiKey(async (req: ApiKeyRequest, ctx: RouteContext) => {
    const { id } = await ctx.params;
    const cancelled = await cancelBooking(id, req.apiKey.restaurantId);
    return NextResponse.json({ data: cancelled });
  }, { permission: 'bookings:write' })
);
