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 { updateBookingSchema } from '@server/validators/bookings.validator';
import { getBooking, updateBooking, cancelBooking, deleteBooking } from '@server/services/bookings.service';

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

export const PATCH = withErrorHandler(
  withAuth(
    withValidationAuthed(updateBookingSchema, async (req, ctx: RouteContext) => {
      const { id } = await ctx.params;
      const body = req.parsedBody;

      if (body.status === 'cancelled') {
        const booking = await cancelBooking(id, req.session.restaurantId!);
        return NextResponse.json({ booking });
      }

      const booking = await updateBooking(id, req.session.restaurantId!, body as Record<string, unknown>);
      return NextResponse.json({ booking });
    })
  )
);

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