import { apiRequest } from '@/shared/api/httpClient';
import { ApiListResponse } from '@/shared/types/api';
import {
  UserProgressDeleteResponse,
  UserProgressDto,
  UserProgressMutationDto,
  UserProgressType,
} from '@/shared/types/userProgress';

const USER_PROGRESS_PATH = '/user_progress';

function createProgressQuery(progressType: UserProgressType, itemId?: string): string {
  const params = new URLSearchParams({ progress_type: progressType });

  if (itemId) {
    params.set('item_id', itemId);
  }

  return params.toString();
}

export function listUserProgress(
  progressType: UserProgressType,
  itemId?: string,
): Promise<ApiListResponse<UserProgressDto>> {
  return apiRequest<ApiListResponse<UserProgressDto>>(
    `${USER_PROGRESS_PATH}?${createProgressQuery(progressType, itemId)}`,
  );
}

export function upsertUserProgress(request: UserProgressMutationDto): Promise<UserProgressDto> {
  return apiRequest<UserProgressDto>(USER_PROGRESS_PATH, {
    method: 'POST',
    body: { data: request },
  });
}

export function deleteUserProgressByItem(
  progressType: UserProgressType,
  itemId: string,
): Promise<UserProgressDeleteResponse> {
  return apiRequest<UserProgressDeleteResponse>(
    `${USER_PROGRESS_PATH}/by-item?${createProgressQuery(progressType, itemId)}`,
    { method: 'DELETE' },
  );
}
