/**
 * An activity "line" on the Movement Dashboard (booking × activity ×
 * ticket × date × booking row) is stored as one booking_activity_items
 * row per age group. The planner shows the line under ONE of those rows
 * and keys every MD write to it — the suppliers[] junction (extra
 * suppliers, cash collection scope) lives on that row only.
 *
 * Postgres returns the sibling rows in no fixed order (they tie on slot
 * and sort_order), so the shown row used to flip between loads and the
 * line's extra suppliers vanished / got saved twice (client 2026-10-29).
 * This picks the row deterministically:
 *   1. the row that already owns the most junction rows,
 *   2. then adult → senior → child → other age group,
 *   3. then the lowest id.
 */

const AGE_RANK: Record<string, number> = { adult: 0, senior: 1, child: 2 };

export function activityLineKey(ai: {
  booking_id: string;
  activity_id: string;
  ticket_id?: string | null;
  date: unknown;
  sort_order?: number | null;
}): string {
  return `${ai.booking_id}_${ai.activity_id}_${ai.ticket_id || 'none'}_${String(ai.date)}_${ai.sort_order ?? 0}`;
}

export function pickActivityLineOwner<T extends { id: string; age_group?: string | null }>(
  rows: T[],
  junctionCount: (id: string) => number,
): T {
  return rows.reduce((best, r) => {
    const dj = junctionCount(r.id) - junctionCount(best.id);
    if (dj !== 0) return dj > 0 ? r : best;
    const ra = AGE_RANK[r.age_group ?? ''] ?? 3;
    const ba = AGE_RANK[best.age_group ?? ''] ?? 3;
    if (ra !== ba) return ra < ba ? r : best;
    return r.id < best.id ? r : best;
  });
}

/**
 * Same rows, each line's owner first (lines keep their first-seen
 * order) — the planner builds a line from its first row.
 */
export function orderActivityRowsOwnerFirst<
  T extends {
    id: string;
    age_group?: string | null;
    booking_id: string;
    activity_id: string;
    ticket_id?: string | null;
    date: unknown;
    sort_order?: number | null;
  },
>(rows: T[], junctionCount: (id: string) => number): T[] {
  const lines = new Map<string, T[]>();
  for (const r of rows) {
    const k = activityLineKey(r);
    const list = lines.get(k);
    if (list) list.push(r);
    else lines.set(k, [r]);
  }
  return [...lines.values()].flatMap((list) => {
    const owner = pickActivityLineOwner(list, junctionCount);
    return [owner, ...list.filter((r) => r !== owner)];
  });
}
