import { NextResponse } from 'next/server';

import { withAuth, withPermission } from '@/lib/api/helpers';
import { errorResponse } from '@/lib/errors';
import { getBerthHeatRanking } from '@/lib/services/berth-heat.service';

/**
 * GET /api/v1/dashboard/berth-heat
 *
 * Returns the top-N berths by active interest count, sorted hottest-
 * first. Drives the BerthHeatWidget on the dashboard and the future
 * heatmap visualization.
 */
export const GET = withAuth(
  withPermission('reports', 'view_dashboard', async (req, ctx) => {
    try {
      const url = new URL(req.url);
      const limit = Math.max(1, Math.min(50, Number(url.searchParams.get('limit') ?? '20')));
      const rows = await getBerthHeatRanking(ctx.portId, limit);
      return NextResponse.json({ data: { rows } });
    } catch (error) {
      return errorResponse(error);
    }
  }),
);
