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

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

export const getPriorityDestinationTaskId = (
  items: TaskItemType[],
  sourceId: string,
  destIndex: number,
  removeSource = true,
): string | null => {
  const sorted = [...items].sort((a, b) => getTaskSortOrder(a) - getTaskSortOrder(b));
  const sourceIndex = sorted.findIndex((item) => item.id === sourceId);

  if (removeSource && sourceIndex === destIndex) return null;

  const list = removeSource ? sorted.filter((item) => item.id !== sourceId) : sorted;
  if (list.length === 0) return null;

  if (destIndex >= list.length) {
    return list[list.length - 1].id;
  }

  return list[destIndex].id;
};
