import type { Task } from "../types";

export const reorderTasks = (
  tasks: Task[],
  taskId: string,
  destColumnId: string,
  destIndex: number,
): Task[] => {
  const task = tasks.find((t) => t.id === taskId);
  if (!task) return tasks;

  const sourceColumnId = task.columnId;
  const without = tasks.filter((t) => t.id !== taskId);

  const destColumnTasks = without
    .filter((t) => t.columnId === destColumnId)
    .sort((a, b) => a.order - b.order);

  destColumnTasks.splice(destIndex, 0, { ...task, columnId: destColumnId });

  const updatedDest = destColumnTasks.map((t, i) => ({ ...t, order: i }));

  if (sourceColumnId === destColumnId) {
    const rest = without.filter((t) => t.columnId !== destColumnId);
    return [...rest, ...updatedDest];
  }

  const sourceTasks = without
    .filter((t) => t.columnId === sourceColumnId)
    .sort((a, b) => a.order - b.order)
    .map((t, i) => ({ ...t, order: i }));

  const rest = without.filter(
    (t) => t.columnId !== destColumnId && t.columnId !== sourceColumnId,
  );

  return [...rest, ...sourceTasks, ...updatedDest];
};
