/**
 * Shared helper that turns an interest's full berth list into the display
 * label surfaced everywhere the record is named (header, kanban card, list
 * rows, search results, picker chips). Mirrors the EOI / Documents-Hub
 * idiom: consecutive runs collapse to a hyphenated range, separate runs
 * comma-join, and an over-cap fallback degrades to "<first> + N more".
 *
 *   deriveInterestBerthLabel([])                       -> null
 *   deriveInterestBerthLabel(['A1'])                   -> 'A1'
 *   deriveInterestBerthLabel(['A1','A2','A3'])         -> 'A1-A3'
 *   deriveInterestBerthLabel(['A1','A3'])              -> 'A1, A3'
 *   deriveInterestBerthLabel(['A1','A3','B5','B6'])    -> 'A1, A3, B5-B6'
 *   deriveInterestBerthLabel(['A1','A3','A5','A7','A9','A11'])
 *                                                      -> 'A1 + 5 more'
 *
 * Truncation triggers when, post-range-collapse, the segment count exceeds
 * MAX_SEGMENTS - keeps the button / header from overflowing.
 */
import { formatBerthRange } from '@/lib/templates/berth-range';

const MAX_SEGMENTS = 5;

export function deriveInterestBerthLabel(
  mooringNumbers: readonly (string | null | undefined)[] | null | undefined,
): string | null {
  if (!mooringNumbers) return null;
  const clean = mooringNumbers.filter((m): m is string => !!m && m.trim().length > 0);
  if (clean.length === 0) return null;

  const compact = formatBerthRange(clean);
  if (!compact) return null;

  const segments = compact.split(', ');
  if (segments.length <= MAX_SEGMENTS) return compact;

  // Over-cap: degrade to "first + N more" against the total berth count.
  const first = segments[0]!;
  const remaining = clean.length - 1;
  return `${first} + ${remaining} more`;
}
