import { NextResponse } from 'next/server';

import { withAuth, withPermission } from '@/lib/api/helpers';
import { parseQuery } from '@/lib/api/route-helpers';
import { errorResponse } from '@/lib/errors';
import { listInterestsForBoard } from '@/lib/services/interests.service';
import { boardFiltersSchema } from '@/lib/validators/interests';

/**
 * Board (kanban) endpoint - returns every active interest for the port
 * with a minimal projection (id, clientName, mooring, leadCategory,
 * stage, updatedAt). No pagination: the kanban renders the whole
 * pipeline at once. The service hard-caps at 5000 rows to keep payload
 * size bounded; if `truncated: true` the UI surfaces a banner.
 *
 * Filter params are a strict subset of the list endpoint - see
 * boardFiltersSchema. `pipelineStage` and `includeArchived` are
 * intentionally rejected at validation time.
 */
export const GET = withAuth(
  withPermission('interests', 'view', async (req, ctx) => {
    try {
      const filters = parseQuery(req, boardFiltersSchema);
      const result = await listInterestsForBoard(ctx.portId, filters);
      // L34 carve-out: deliberate bare-shape response (NOT the `{ data }`
      // envelope). The pipeline board reads the column/lane fields off the
      // JSON root; wrapping them would break the consumer. Left as-is.
      return NextResponse.json(result);
    } catch (error) {
      return errorResponse(error);
    }
  }),
);
