import { datesMatch } from "./timelineLivePreview.js";

export type AllocationMovedSnapshotLike = {
  allocationId: string;
  mutationAllocationId: string;
  projectName: string;
  before: { startDate: Date; endDate: Date };
  after: { startDate: Date; endDate: Date };
};

type AllocDragFinalizeLike = {
  mode: "move" | "resize-start" | "resize-end";
  scope: "allocation" | "segment";
  allocationId: string | null;
  mutationAllocationId: string | null;
  projectName: string | null;
  allocationStartDate: Date | null;
  allocationEndDate: Date | null;
  originalStartDate: Date | null;
  originalEndDate: Date | null;
  currentStartDate: Date | null;
  currentEndDate: Date | null;
  pointerDeltaX: number;
  daysDelta: number;
};

export function hasAllocationDateChange(alloc: AllocDragFinalizeLike): boolean {
  if (!alloc.originalStartDate || !alloc.currentStartDate || !alloc.originalEndDate || !alloc.currentEndDate) {
    return false;
  }

  return (
    alloc.originalStartDate.getTime() !== alloc.currentStartDate.getTime() ||
    alloc.originalEndDate.getTime() !== alloc.currentEndDate.getTime()
  );
}

export function shouldTreatAllocationDragAsClick(
  alloc: Pick<AllocDragFinalizeLike, "mode" | "daysDelta" | "pointerDeltaX">,
  clickThresholdPx: number,
): boolean {
  return alloc.mode === "move" && alloc.daysDelta === 0 && Math.abs(alloc.pointerDeltaX) <= clickThresholdPx;
}

export function requiresAllocationFragmentExtraction(
  alloc: Pick<
    AllocDragFinalizeLike,
    "scope" | "originalStartDate" | "allocationStartDate" | "originalEndDate" | "allocationEndDate"
  >,
): boolean {
  return (
    alloc.scope === "segment" &&
    (!datesMatch(alloc.originalStartDate, alloc.allocationStartDate) ||
      !datesMatch(alloc.originalEndDate, alloc.allocationEndDate))
  );
}

export function buildAllocationMovedSnapshot(
  alloc: Pick<
    AllocDragFinalizeLike,
    | "allocationId"
    | "mutationAllocationId"
    | "projectName"
    | "originalStartDate"
    | "originalEndDate"
    | "currentStartDate"
    | "currentEndDate"
  >,
): AllocationMovedSnapshotLike | null {
  if (
    !alloc.allocationId ||
    !alloc.originalStartDate ||
    !alloc.originalEndDate ||
    !alloc.currentStartDate ||
    !alloc.currentEndDate
  ) {
    return null;
  }

  return {
    allocationId: alloc.allocationId,
    mutationAllocationId: alloc.mutationAllocationId ?? alloc.allocationId,
    projectName: alloc.projectName ?? "",
    before: {
      startDate: alloc.originalStartDate,
      endDate: alloc.originalEndDate,
    },
    after: {
      startDate: alloc.currentStartDate,
      endDate: alloc.currentEndDate,
    },
  };
}
