import { CourseStatus } from '../courses/types';

import {
  type Path,
  type PathCourseListItem,
  PathCourseStatus,
  PathOrderBy,
  PathStatus,
} from './types';

export const getStatusOrderBy = (status: PathStatus) => {
  if (status === PathStatus.ALL) return PathOrderBy.DEFAULT;
  if (status === PathStatus.IN_PROGRESS) return PathOrderBy.PROGRESS;
  return PathOrderBy.TITLE;
};

export const isPathCourseBlocked = (path: Path, courseIndex: number) => {
  if (!path.courses || !path.isSequential) return false;

  for (let i = 0; i < courseIndex; i++) {
    if (path.courses[i].status !== CourseStatus.FINISHED) return true;
  }

  return false;
};

export const getPathCourseStatus = (path: Path, courseIndex: number) => {
  if (!path.courses) return null;

  const course = path.courses[courseIndex];

  if (course.status === CourseStatus.FINISHED) {
    return PathCourseStatus.FINISHED;
  }
  if (isPathCourseBlocked(path, courseIndex)) {
    return PathCourseStatus.BLOCKED;
  }
  if (course.status === CourseStatus.IN_PROGRESS) {
    return PathCourseStatus.IN_PROGRESS;
  }
  if (course.status === CourseStatus.PENDING_SIGNATURE) {
    return PathCourseStatus.IN_PROGRESS;
  }

  return PathCourseStatus.PENDING;
};

export const getFinishedPathCoursesAmount = (courses: PathCourseListItem[]) => {
  return courses.reduce((acc, course) => {
    if (isPathCourseFinished(course)) acc++;
    return acc;
  }, 0);
};

export const isPathCourseFinished = (course: PathCourseListItem) =>
  course.status === CourseStatus.FINISHED;

export const isPathCoursePending = (course: PathCourseListItem) =>
  [CourseStatus.PENDING, CourseStatus.IN_PROGRESS].includes(course.status);

export const getPathStartCourse = (path: Path) => {
  if (path.status === PathStatus.FINISHED) return path.courses[0];
  return path.courses.find(isPathCoursePending);
};

export const showCertificate = (path: Path) =>
  path.status === PathStatus.FINISHED && path.issueCertificate;
