import type { TaskItemType } from "../task/types/TaskTypes";

const getTaskSortOrder = (task: TaskItemType) => task.order ?? task.priority ?? 0;

export const reorderTaskItems = (
  tasks: TaskItemType[],
  taskId: string,
  destIndex: number,
): TaskItemType[] => {
  const task = tasks.find((item) => item.id === taskId);
  if (!task) return tasks;

  const without = tasks.filter((item) => item.id !== taskId);
  const sorted = [...without].sort((a, b) => getTaskSortOrder(a) - getTaskSortOrder(b));
  sorted.splice(destIndex, 0, task);

  return sorted.map((item, index) => ({ ...item, order: index, priority: index }));
};
