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

import { withAuth, withPermission } from '@/lib/api/helpers';
import { parseBody } from '@/lib/api/route-helpers';
import { errorResponse } from '@/lib/errors';
import { recommendBerths } from '@/lib/services/berth-recommender.service';

/**
 * POST body - mirrors `RecommendBerthsArgs` minus the `interestId` (route
 * param) and `portId` (resolved from the auth context - never trust a
 * client-supplied port, plan §14.10).
 */
const recommendBerthsSchema = z
  .object({
    topN: z.number().int().min(1).max(999).optional(),
    // F18: accept `limit` as a friendlier alias for `topN`. The audit
    // sent `{limit: 3}` and was silently ignored; conventional API users
    // expect the limit name. Both resolve to the same internal value.
    limit: z.number().int().min(1).max(999).optional(),
    maxOversizePct: z.number().min(0).max(1000).optional(),
    showLateStage: z.boolean().optional(),
    amenityFilters: z
      .object({
        minPowerCapacityKw: z.number().min(0).optional(),
        requiredVoltage: z.number().int().min(0).optional(),
        requiredAccess: z.string().min(1).optional(),
        requiredMooringType: z.string().min(1).optional(),
        requiredCleatCapacity: z.string().min(1).optional(),
      })
      .optional(),
  })
  .transform(({ limit, topN, ...rest }) => ({
    ...rest,
    topN: topN ?? limit,
  }));

// POST /api/v1/interests/[id]/recommend-berths
export const POST = withAuth(
  withPermission('interests', 'view', async (req, ctx, params) => {
    try {
      const body = await parseBody(req, recommendBerthsSchema);
      const data = await recommendBerths({
        interestId: params.id!,
        portId: ctx.portId,
        ...body,
      });
      return NextResponse.json({ data });
    } catch (error) {
      return errorResponse(error);
    }
  }),
);
