import { finalizeRangeSelection, type RangeSelectionResult } from "./timelineRangeSelection.js";

type RangeStateLike = {
  isSelecting: boolean;
  resourceId: string | null;
  startDate: Date | null;
  currentDate: Date | null;
  suggestedProjectId: string | null;
  startClientX: number;
};

export type RangeReleaseResolution<TState> =
  | { kind: "noop"; nextState: TState; selection: null }
  | { kind: "complete"; nextState: TState; selection: RangeSelectionResult };

export function resolveRangeSelectionRelease<TState extends RangeStateLike>(
  state: TState,
  anchorX: number,
  anchorY: number,
  initialState: TState,
): RangeReleaseResolution<TState> {
  const selection = finalizeRangeSelection(state, anchorX, anchorY);
  if (!selection) {
    return {
      kind: "noop",
      nextState: state,
      selection: null,
    };
  }

  return {
    kind: "complete",
    nextState: initialState,
    selection,
  };
}

export function resolveRangeSelectionCancel<TState extends RangeStateLike>(
  state: TState,
  initialState: TState,
): { didReset: boolean; nextState: TState } {
  if (!state.isSelecting) {
    return {
      didReset: false,
      nextState: state,
    };
  }

  return {
    didReset: true,
    nextState: initialState,
  };
}
