import { GridBaseRow } from './types';

/**
 * Reorders rows by removing movedRows from the array and inserting them at the target position.
 * @param rows - The current row array.
 * @param movedRows - Rows to move, in desired insertion order (typically display order).
 * @param targetRow - The row to insert relative to.
 * @param direction - -1 inserts above targetRow, 1 inserts below targetRow.
 * @returns A new array with the rows reordered, or the original array if the operation is a no-op.
 */
export function reorderRows<T extends GridBaseRow>(rows: T[], movedRows: T[], targetRow: T, direction: -1 | 1): T[] {
  if (movedRows.length === 0) return rows;

  const movedIds = new Set(movedRows.map((r) => r.id));

  // If targetRow is one of the moved rows, no-op
  if (movedIds.has(targetRow.id)) return rows;

  // Remove moved rows from the array
  const remaining = rows.filter((r) => !movedIds.has(r.id));

  // Find where to insert relative to the target
  const targetIndex = remaining.findIndex((r) => r.id === targetRow.id);
  if (targetIndex === -1) return rows;

  const insertIndex = direction === 1 ? targetIndex + 1 : targetIndex;

  // Insert movedRows at the calculated position
  const result = [...remaining];
  result.splice(insertIndex, 0, ...movedRows);
  return result;
}
