import { useMemo } from 'react';
import { useQuery } from 'react-query';

import { EMPLOYEE_LIFECYCLE_STALE_TIME } from '../constants';
import { employeeLifecycleKeys } from '../queries';
import { getJourneySteps } from '../services';
import { JourneyProcessStatusType, JourneyStepsSections } from '../types';
import { groupStepsBySection } from '../utils';

export const useGetJourneySteps = (journeyId: number | undefined) => {
  const { data, ...query } = useQuery({
    queryKey: employeeLifecycleKeys.journeys.steps(journeyId!),
    queryFn: () => {
      if (!journeyId) throw new Error('Journey ID is required');
      return getJourneySteps(journeyId);
    },
    select: response => response.data,
    enabled: !!journeyId,
    staleTime: EMPLOYEE_LIFECYCLE_STALE_TIME,
  });

  const stepSections = useMemo(
    () => groupStepsBySection({ steps: data?.steps || [] }),
    [data?.steps],
  ) as JourneyStepsSections;

  return {
    ...query,
    processName: data?.processName || '',
    processStatus: data?.processStatus as JourneyProcessStatusType,
    steps: stepSections,
  };
};
