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 { createBookingSchema } from '@server/validators/bookings.validator';
import { listBookings, createBooking } from '@server/services/bookings.service';

export const GET = withErrorHandler(
  withAuth(async (req: AuthedRequest) => {
    const { restaurantId, branchId } = req.session;
    const url = new URL(req.url);
    const p = url.searchParams;

    const result = await listBookings({
      restaurantId: restaurantId!,
      branchId: p.get('branch_id') ?? branchId ?? undefined,
      customerId: p.get('customer_id') ?? undefined,
      status: p.get('status') ?? undefined,
      date: p.get('date') ?? undefined,
      search: p.get('search') ?? undefined,
      page: parseInt(p.get('page') ?? '1', 10),
      limit: parseInt(p.get('limit') ?? '20', 10),
      sortField: p.get('sort_field') ?? undefined,
      sortDir: p.get('sort_dir') ?? undefined,
    });

    return NextResponse.json({ bookings: result.data, total: result.total, page: result.page, limit: result.limit, pages: result.pages });
  })
);

export const POST = withErrorHandler(
  withAuth(
    withValidationAuthed(createBookingSchema, async (req) => {
      const body = req.parsedBody as Record<string, unknown>;
      const data = { branch_id: req.session.branchId ?? null, ...body };
      const booking = await createBooking(req.session.restaurantId!, data);
      return NextResponse.json({ booking }, { status: 201 });
    })
  )
);
