/**
 * Route handler for `/api/v1/berths/price-reconcile/apply` (CM-2 Part A).
 *
 * Writes a rep-approved slice of parsed prices to the berths. In handlers.ts so
 * integration tests can call it directly.
 */

import { NextResponse } from 'next/server';
import { z } from 'zod';

import { type RouteHandler } from '@/lib/api/helpers';
import { parseBody } from '@/lib/api/route-helpers';
import { errorResponse } from '@/lib/errors';
import { applyBulkBerthPrices } from '@/lib/services/berth-price-reconcile.service';

const bodySchema = z.object({
  approvals: z
    .array(
      z.object({
        berthId: z.string().min(1),
        price: z.number().nonnegative(),
        currency: z.string().min(1).max(8),
      }),
    )
    .min(1),
});

export const postHandler: RouteHandler = async (req, ctx) => {
  try {
    const body = await parseBody(req, bodySchema);
    const result = await applyBulkBerthPrices(ctx.portId, body.approvals, ctx.userId);
    return NextResponse.json({ data: result });
  } catch (error) {
    return errorResponse(error);
  }
};
