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 { parseListParams, buildListEnvelope, CursorError, cursorErrorResponse } from '@server/middleware/v1Pagination';
import { createBookingSchema, CreateBookingInput } from '@server/validators/bookings.validator';
import { listBookings, createBooking } from '@server/services/bookings.service';

export const GET = withV1ErrorHandler(
  withApiKey(async (req: ApiKeyRequest) => {
    const url = new URL(req.url);
    let pager;
    try { pager = parseListParams(url); }
    catch (e) { if (e instanceof CursorError) return cursorErrorResponse(e); throw e; }

    const result = await listBookings({
      restaurantId: req.apiKey.restaurantId,
      branchId: url.searchParams.get('branch_id') ?? undefined,
      customerId: url.searchParams.get('customer_id') ?? undefined,
      status: url.searchParams.get('status') ?? undefined,
      date: url.searchParams.get('date') ?? undefined,
      search: url.searchParams.get('search') ?? undefined,
      page: pager.page,
      limit: pager.limit,
      sortField: url.searchParams.get('sort') ?? undefined,
      sortDir: url.searchParams.get('dir') ?? undefined,
    });
    return NextResponse.json(buildListEnvelope(result.data, pager.page, pager.limit));
  }, { permission: 'bookings:read' })
);

export const POST = withV1ErrorHandler(
  withApiKey(
    withV1Validation(createBookingSchema, async (req: ParsedRequest<CreateBookingInput>) => {
      const apiReq = req as ParsedRequest<CreateBookingInput> & ApiKeyRequest;
      const booking = await createBooking(
        apiReq.apiKey.restaurantId,
        req.parsedBody as unknown as Record<string, unknown>
      );
      return NextResponse.json({ data: booking }, { status: 201 });
    }),
    { permission: 'bookings:write' }
  )
);
