import { NextResponse } from 'next/server';

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

/**
 * POST /api/v1/berths/bulk-update-prices
 *
 * Bulk update berth prices in a single transaction (up to 500 per call).
 * Gated by `berths.update_prices`. Returns counts so the UI can present
 * "Updated N · Unchanged M · Missing K" feedback.
 *
 * Audit: one `audit_log` row per actually-updated berth (idempotent -
 * berths whose new price matches the existing value are skipped and
 * counted as `unchanged`).
 */
export const POST = withAuth(
  withPermission('berths', 'update_prices', async (req, ctx) => {
    try {
      const body = await parseBody(req, bulkUpdateBerthPricesSchema);
      const result = await bulkUpdateBerthPrices(ctx.portId, body, {
        userId: ctx.userId,
        portId: ctx.portId,
        ipAddress: ctx.ipAddress,
        userAgent: ctx.userAgent,
      });
      return NextResponse.json({ data: result });
    } catch (error) {
      return errorResponse(error);
    }
  }),
);
