import { NextResponse } from 'next/server';

import { withAuth, withPermission } from '@/lib/api/helpers';
import { parseBody } from '@/lib/api/route-helpers';
import { updateBerthPriceSchema } from '@/lib/validators/berths';
import { updateBerthPrice } from '@/lib/services/berths.service';
import { errorResponse } from '@/lib/errors';

/**
 * PATCH /api/v1/berths/[id]/price
 *
 * Focused price-update endpoint gated by the dedicated
 * `berths.update_prices` permission. Lets a role mutate berth pricing
 * without granting the full `berths.edit` surface.
 *
 * Always audited (one `audit_log` row per call with
 * `field_changed='price'` and the before/after values).
 */
export const PATCH = withAuth(
  withPermission('berths', 'update_prices', async (req, ctx, params) => {
    try {
      const body = await parseBody(req, updateBerthPriceSchema);
      const updated = await updateBerthPrice(params.id!, ctx.portId, body, {
        userId: ctx.userId,
        portId: ctx.portId,
        ipAddress: ctx.ipAddress,
        userAgent: ctx.userAgent,
      });
      return NextResponse.json({ data: updated });
    } catch (error) {
      return errorResponse(error);
    }
  }),
);
