import api from 'src/config/api';
import {
  type Course,
  type CourseCategory,
  type CourseList,
  type CourseListItem,
  CourseStatus,
  CourseTypes,
  type FinishTaskResponse,
  type GetCourseCategoriesParams,
  type SignCourseData,
  type SurveyFormData,
  type SurveyQuestion,
  type Task,
} from 'src/pages/dashboard/learning/courses/types';
import { filterCourseCategories } from 'src/utils/courses';
import { formatPagination, type PaginatedResponse } from 'src/utils/pagination';

// 'formatPage' is added for retrocompatibility.
export const getCourses = (
  { status, search, order, orderBy, sort, type, ...pagination }: CourseList,
  formatPage: boolean = true,
) => {
  const isAllTab = status === CourseStatus.ALL;
  const [sortOrderBy, sortOrder] = sort?.split('/') || [];
  const formatedPagination = formatPage
    ? formatPagination(pagination)
    : pagination;

  return api.get<PaginatedResponse<CourseListItem>>('courses', {
    params: {
      ...formatedPagination,
      q: search || undefined,
      status: isAllTab ? undefined : status,
      isObligatory: type ? type === CourseTypes.REQUIRED : undefined,
      sortingOption: sortOrderBy || orderBy,
      order: sortOrder || order,
    },
  });
};

export const getCourseCategories = async (
  params: GetCourseCategoriesParams,
) => {
  const response = await api.get<PaginatedResponse<CourseCategory>>(
    'courses/categories',
    { params },
  );

  return filterCourseCategories(response);
};

export const getCourse = (id: number) => api.get<Course>(`courses/${id}`);

export const initCourse = (id: number | string) =>
  api.post(`courses/${id}/init`);

export const initCourseTask = (taskId: number | string, tag: string) =>
  api.post(
    `courses/tasks/init/${taskId}`,
    {},
    {
      params: {
        tag,
      },
    },
  );

export const finishCourseTask = (
  taskId: number | string,
  tag: string,
  body: Object = {},
) =>
  api.post<FinishTaskResponse>(`courses/tasks/finish/${taskId}`, body, {
    params: {
      tag,
    },
  });

export const getEvaluationQuestions = (taskId: number | string, tag: string) =>
  api.get(`courses/tasks/evaluation-questions/${taskId}`, {
    params: {
      tag,
    },
  });

export const getCourseTask = (taskId: number | string, tag: string) =>
  api.get<Task>(`courses/tasks/${taskId}`, {
    params: {
      tag,
    },
  });

export const getCourseSurvey = (id: number | string) =>
  api.get<SurveyQuestion[]>(`courses/${id}/satisfaction-survey`);

export const sendCourseSurvey = (id: number | string, body: SurveyFormData) =>
  api.post(`courses/${id}/satisfaction-survey`, body);

export const getCertificate = (id: number | string) =>
  api.post<Course>(`courses/${id}/cert-generation`);

export const signCourse = (id: number | string, body: SignCourseData) =>
  api.post(`courses/${id}/sign`, body);
