import { buildProjectShiftMutationInput } from "./timelineProjectDrag.js";
import { preserveLivePreview, type LivePreviewSession } from "./timelineLivePreview.js";

type MutableCurrent<T> = { current: T };
type ProjectDragFinalizeLike = Parameters<typeof buildProjectShiftMutationInput>[0] & { isDragging: boolean };

export function finalizeProjectDrag({
  clientX,
  mode = "mutate",
  dragRef,
  previewRef,
  updatePosition,
  clearSession,
  mutate,
  mutateAsync,
}: {
  clientX: number;
  mode?: "mutate" | "mutateAsync";
  dragRef: MutableCurrent<ProjectDragFinalizeLike>;
  previewRef: MutableCurrent<LivePreviewSession | null>;
  updatePosition: (clientX: number) => void;
  clearSession: () => void;
  mutate: (input: { projectId: string; newStartDate: Date; newEndDate: Date }) => void;
  mutateAsync: (input: { projectId: string; newStartDate: Date; newEndDate: Date }) => Promise<unknown>;
}) {
  updatePosition(clientX);
  const finalDrag = dragRef.current;
  if (!finalDrag.isDragging) return null;

  const mutationInput = buildProjectShiftMutationInput(finalDrag);
  if (finalDrag.daysDelta !== 0) preserveLivePreview(previewRef.current);
  clearSession();

  if (!mutationInput) return null;
  if (mode === "mutateAsync") return mutateAsync(mutationInput);
  mutate(mutationInput);
  return null;
}
