/**
 * Legacy-shape helper for callers (invoice lines, audit renderer,
 * template variables) that still expect a single room_type / meal_plan
 * / num_rooms / pax_per_room per stay. Returns the FIRST period as the
 * "primary" — matches how the flat pre-split model displayed the stay.
 *
 * Callers should migrate away over time (invoices could list every
 * period), but this keeps the transition non-breaking.
 */
export interface HotelPrimaryPeriodShape {
  room_type: string;
  meal_plan: string;
  num_rooms: number;
  pax_per_room: number;
}

interface PeriodLike {
  sort_order?: number;
  room_type?: string | null;
  meal_plan?: string | null;
  num_rooms?: number | null;
  pax_per_room?: number | null;
}

export function pickPrimaryPeriod(
  periods: PeriodLike[] | null | undefined,
): HotelPrimaryPeriodShape {
  if (!Array.isArray(periods) || periods.length === 0) {
    return { room_type: '', meal_plan: '', num_rooms: 1, pax_per_room: 2 };
  }
  const sorted = [...periods].sort(
    (a, b) => (a.sort_order ?? 0) - (b.sort_order ?? 0),
  );
  const p = sorted[0];
  return {
    room_type: p.room_type ?? '',
    meal_plan: p.meal_plan ?? '',
    num_rooms: p.num_rooms ?? 1,
    pax_per_room: p.pax_per_room ?? 2,
  };
}

/** Sum of num_rooms across all periods — the "total rooms on this
 *  stay" number that legacy invoices used to read off the flat column. */
export function sumTotalRooms(periods: PeriodLike[] | null | undefined): number {
  if (!Array.isArray(periods) || periods.length === 0) return 1;
  return periods.reduce((s, p) => s + Math.max(1, Number(p.num_rooms) || 1), 0);
}
