import type { Point } from '@house-plan-maker/shared';
import type { MeasurementState, MeasurementResult } from '../types';
import { distance } from '../utils/geometry';

/** Start a new measurement from the given point. */
export function startMeasurement(point: Point): MeasurementState {
  return {
    startPoint: point,
    endPoint: point,
    distance: 0,
  };
}

/** Update the measurement end point and recalculate distance. */
export function updateMeasurement(
  state: MeasurementState,
  point: Point,
): MeasurementState {
  return {
    ...state,
    endPoint: point,
    distance: distance(state.startPoint, point),
  };
}

/** Finalize the measurement and return the result. */
export function finishMeasurement(state: MeasurementState): MeasurementResult {
  return {
    startPoint: state.startPoint,
    endPoint: state.endPoint,
    distance: distance(state.startPoint, state.endPoint),
  };
}
