import { NextResponse } from 'next/server';

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

/**
 * POST /api/v1/berths/bulk-add
 *
 * Bulk-insert berths for new-port setup. Cap of 500 rows per call;
 * the service rejects with ConflictError on first duplicate (within
 * the input array or against existing port rows). Wizard UI lives at
 * /[portSlug]/admin/berths/bulk-add.
 */
export const POST = withAuth(
  // F13: aligned with the seed-permissions scope (`berths.import`).
  // The previous `berths.create` was a phantom key - not in the role
  // matrix, so non-super-admins silently failed permission resolution.
  withPermission('berths', 'import', async (req, ctx) => {
    try {
      const input = await parseBody(req, bulkAddBerthsSchema);
      const result = await bulkAddBerths(ctx.portId, input.berths, {
        userId: ctx.userId,
        portId: ctx.portId,
        ipAddress: ctx.ipAddress,
        userAgent: ctx.userAgent,
      });
      return NextResponse.json({ data: result });
    } catch (error) {
      return errorResponse(error);
    }
  }),
);
