import {
  buildAllocationMovedSnapshot,
  requiresAllocationFragmentExtraction,
  type AllocationMovedSnapshotLike,
} from "./timelineAllocationFinalize.js";

type AllocationActionLike = {
  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;
};

export function buildAllocationBlockClickInfo(
  alloc: Pick<
    AllocationActionLike,
    "allocationId" | "projectId" | "projectName" | "originalStartDate" | "originalEndDate"
  >,
): { allocationId: string; projectId: string; projectName: string; startDate: Date; endDate: Date } | null {
  if (!alloc.allocationId || !alloc.originalStartDate || !alloc.originalEndDate) {
    return null;
  }

  return {
    allocationId: alloc.allocationId,
    projectId: alloc.projectId ?? "",
    projectName: alloc.projectName ?? "",
    startDate: alloc.originalStartDate,
    endDate: alloc.originalEndDate,
  };
}

export function buildAllocationMutationPlan(
  alloc: AllocationActionLike,
): {
  activeAllocationId: string;
  currentStartDate: Date;
  currentEndDate: Date;
  baseMutationAllocationId: string;
  requiresExtraction: boolean;
  pendingSnapshot: AllocationMovedSnapshotLike | null;
} | null {
  if (!alloc.allocationId || !alloc.currentStartDate || !alloc.currentEndDate) {
    return null;
  }

  return {
    activeAllocationId: alloc.allocationId,
    currentStartDate: alloc.currentStartDate,
    currentEndDate: alloc.currentEndDate,
    baseMutationAllocationId: alloc.mutationAllocationId ?? alloc.allocationId,
    requiresExtraction: requiresAllocationFragmentExtraction(alloc),
    pendingSnapshot: buildAllocationMovedSnapshot(alloc),
  };
}
