import { buildAllocationBlockClickInfo, buildAllocationMutationPlan } from "./timelineAllocationActions.js";
import { hasAllocationDateChange, shouldTreatAllocationDragAsClick } from "./timelineAllocationFinalize.js";

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

type AllocationBlockClickInfo = ReturnType<typeof buildAllocationBlockClickInfo>;
type AllocationMutationPlan = NonNullable<ReturnType<typeof buildAllocationMutationPlan>>;

export type AllocationReleaseOutcome =
  | { kind: "ignore"; preservePreview: false }
  | { kind: "reset"; preservePreview: boolean }
  | { kind: "shift-click"; allocationId: string; preservePreview: boolean }
  | { kind: "click"; clickInfo: NonNullable<AllocationBlockClickInfo>; preservePreview: boolean }
  | { kind: "mutation"; mutationPlan: AllocationMutationPlan; preservePreview: true };

export function resolveAllocationRelease(
  alloc: AllocationReleaseLike,
  { clickThresholdPx, wasShift }: { clickThresholdPx: number; wasShift: boolean },
): AllocationReleaseOutcome {
  if (!alloc.isActive) {
    return { kind: "ignore", preservePreview: false };
  }

  const preservePreview = hasAllocationDateChange(alloc);
  const shouldTreatAsClick = shouldTreatAllocationDragAsClick(alloc, clickThresholdPx);

  if (shouldTreatAsClick && alloc.allocationId) {
    if (wasShift) {
      return { kind: "shift-click", allocationId: alloc.allocationId, preservePreview };
    }

    const clickInfo = buildAllocationBlockClickInfo(alloc);
    if (clickInfo) {
      return { kind: "click", clickInfo, preservePreview };
    }
  }

  if (preservePreview && alloc.allocationId && alloc.currentStartDate && alloc.currentEndDate) {
    const mutationPlan = buildAllocationMutationPlan(alloc);
    if (mutationPlan) {
      return { kind: "mutation", mutationPlan, preservePreview: true };
    }
  }

  return { kind: "reset", preservePreview };
}
