import api from 'src/config/api';
import {
  type LearningAudience,
  type SegmentationPayload,
} from 'src/pages/dashboard/Learning/common/types';
import { getSortingOption } from 'src/pages/dashboard/Learning/common/utils';
import {
  type CreateLearningPath,
  type CreatePathPostType,
  type PathDetail,
  type PathsPagination,
  type PathsResponse,
  type PathsStats,
  type ShowAdminInformation,
} from 'src/pages/dashboard/Learning/Paths/types';
import { formatPagination, type Pagination } from 'src/utils/tableUtils';

export const getPaths = (pagination: PathsPagination) => {
  const { sortingOption } = getSortingOption(
    pagination.order,
    pagination.orderBy,
  );

  const newPagination = {
    ...pagination,
    orderBy: sortingOption,
  } as Pagination;

  return api.get<PathsResponse>('/learning-paths', {
    params: formatPagination(newPagination, 'q'),
  });
};

export const getPath = (id: number) =>
  api.get<PathDetail>(`/learning-paths/${id}`);

export const getPathsStats = () => api.get<PathsStats>('/learning-paths/stats');

export const createPath = (data: CreatePathPostType) =>
  api.post<PathDetail>('/learning-paths', data);

export const updatePath = (id: number, data: CreateLearningPath) =>
  api.put<PathDetail>(`/learning-paths/${id}`, data);

export const updatePartialPath = (
  id: number,
  data: Partial<CreateLearningPath>,
) => api.patch<PathDetail>(`/learning-paths/${id}`, data);

export const assignUsersToPath = (id: number, data: SegmentationPayload) =>
  api.put(`/learning-paths/${id}/assign-users`, data);

export const deletePath = (id: number) => api.delete(`/learning-paths/${id}`);

export const getShowAdminInformation = () =>
  api.get<ShowAdminInformation>('/learning-paths/show-admin-information');

export const hideAdminInformation = () =>
  api.post('/learning-paths/hide-admin-information');

export const getAudience = (id: number) =>
  api.get<LearningAudience>(`/learning-paths/${id}/audiences`);
