import api from 'src/config/api';
import {
  type CreateLearningSession,
  type DownloadSessionReportParams,
  type EditPartialSessionData,
  type SessionAttendance,
  type SessionAttendanceStats,
  type SessionDetail,
  type SessionsPaginationParams,
  type SessionsStats,
  type SessionTableItem,
  type UpdateLearningSession,
  type UpdateSessionAttendanceParams,
} from 'src/pages/dashboard/Learning/Sessions/types';
import { type PaginatedResponse } from 'src/utils/tableUtils';

import { type SegmentationPayload } from '../common/types';

export const getShowSessionsTutorial = () =>
  api.get<{ showAdminInformation: boolean }>(
    '/learning-sessions/show-admin-information',
  );

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

export const getSessionsStats = () =>
  api.get<SessionsStats>('/learning-sessions/stats');

export const getSessionAttendanceStats = (sessionId: number) =>
  api.get<SessionAttendanceStats>(
    `/learning-sessions/${sessionId}/attendance-stats`,
  );

export const getSessions = (params: SessionsPaginationParams) =>
  api.get<PaginatedResponse<SessionTableItem>>('/learning-sessions', {
    params,
  });

export const getSession = (sessionId: number) =>
  api.get<SessionDetail>(`/learning-sessions/${sessionId}`);

export const createSession = (data: CreateLearningSession) =>
  api.post<SessionDetail>('/learning-sessions', data);

export const updatePartialSession = (
  sessionId: number,
  data: Partial<UpdateLearningSession>,
) => api.patch<SessionDetail>(`/learning-sessions/${sessionId}`, data);

export const assignUsersToSession = (
  sessionId: number,
  data: SegmentationPayload,
) => api.put<void>(`/learning-sessions/${sessionId}/assign-users`, data);

export const deleteSession = (sessionId: number) =>
  api.delete<void>(`/learning-sessions/${sessionId}`);

export const editPartialSession = ({
  sessionId,
  data,
}: EditPartialSessionData) =>
  api.patch<SessionDetail>(`/learning-sessions/${sessionId}`, data);

export const getSessionAttendance = (
  sessionId: number,
  params: SessionsPaginationParams,
) =>
  api.get<PaginatedResponse<SessionAttendance>>(
    `/learning-sessions/${sessionId}/attendance`,
    { params },
  );

export const updateSessionAttendance = (
  sessionId: number,
  params: UpdateSessionAttendanceParams,
) =>
  api.patch<void>(`/learning-sessions/${sessionId}/bulk-attendance`, {
    ...params,
  });

export const downloadSessionReport = ({
  sessionId,
  email,
  includeGroups = [],
  includeUserFields = [],
}: DownloadSessionReportParams) => {
  const params: Record<string, string> = { email };

  if (includeGroups.length > 0) {
    params.groupIds = includeGroups.join(',');
  }

  if (includeUserFields.length > 0) {
    params.userFields = includeUserFields.join(',');
  }

  return api.get<BlobPart>(
    `/learning-sessions/${sessionId}/attendance-report`,
    { params },
  );
};
