import { useNavigate } from 'react-router-dom';

import { logEvent } from 'src/config/logging';
import { EventName } from 'src/types/amplitude';

import useRoutes from '../../hooks/useRoutes';
import { type Path, PathStatus, StartPathEventReason } from '../types';
import { getPathStartCourse } from '../utils';

const useStartPath = (path: Path) => {
  const navigate = useNavigate();
  const routes = useRoutes();

  const getStartCourseId = (courseId?: number) => {
    let courseDetailId = courseId;

    if (!courseId) {
      const course = getPathStartCourse(path);
      courseDetailId = course?.id;
    }

    return courseDetailId;
  };

  const startPath = (courseId?: number) => {
    const courseDetailId = getStartCourseId(courseId);
    if (!courseDetailId) return;

    logEvent(EventName.PATH_STARTED, {
      pathId: path.id,
      resumedFrom:
        path.status === PathStatus.PENDING
          ? StartPathEventReason.NEW
          : StartPathEventReason.RESUMED,
    });

    navigate(routes.courses.detail(courseDetailId));
  };

  return { startPath };
};

export default useStartPath;
