import { NextResponse } from 'next/server';

import type { AuthContext } from '@/lib/api/helpers';
import { parseQuery } from '@/lib/api/route-helpers';
import { errorResponse } from '@/lib/errors';
import { listReservations } from '@/lib/services/berth-reservations.service';
import { listReservationsSchema } from '@/lib/validators/reservations';

/**
 * Port-scoped global list of reservations across all berths. Inner handler
 * lives here so it can be invoked directly from integration tests without
 * the `withAuth(withPermission(...))` wrappers (matches the convention
 * used throughout `src/app/api/v1/*`).
 */
export async function listHandler(req: Request, ctx: AuthContext): Promise<NextResponse> {
  try {
    const query = parseQuery(req as never, listReservationsSchema);
    const result = await listReservations(ctx.portId, query);
    const { page, limit } = query;
    const totalPages = Math.ceil(result.total / limit);
    return NextResponse.json({
      data: result.data,
      pagination: {
        page,
        pageSize: limit,
        total: result.total,
        totalPages,
        hasNextPage: page < totalPages,
        hasPreviousPage: page > 1,
      },
    });
  } catch (error) {
    return errorResponse(error);
  }
}
