import { apiRequest } from '@/shared/api/httpClient';
import { ApiListResponse } from '@/shared/types/api';
import type {
  PersonalityDistributionDto,
  PersonalityCompletionDto,
  PersonalityQuizResultHistoryDto,
  PersonalityQuizResultDto,
  PersonalityQuizResultMutationDto,
} from '@/shared/types/personality';
import type { PersonalityQuizKind } from '@/shared/constants/personality';

const PERSONALITY_RESULTS_PATH = '/personality_quiz_results';

export function getCurrentPersonalityResult(quizKind: PersonalityQuizKind): Promise<PersonalityQuizResultDto | null> {
  return apiRequest<PersonalityQuizResultDto | null>(
    `${PERSONALITY_RESULTS_PATH}/me?${new URLSearchParams({ quiz_kind: quizKind }).toString()}`,
  );
}

export function listCurrentPersonalityResultHistory(): Promise<PersonalityQuizResultHistoryDto> {
  return apiRequest<PersonalityQuizResultHistoryDto>(`${PERSONALITY_RESULTS_PATH}/me/history`);
}

export function saveCurrentPersonalityResult(
  request: PersonalityQuizResultMutationDto,
): Promise<PersonalityQuizResultDto | null> {
  return apiRequest<PersonalityQuizResultDto | null>(`${PERSONALITY_RESULTS_PATH}/me`, {
    method: 'PUT',
    body: { data: request },
  });
}

export function listPersonalityDistribution(campusId?: string): Promise<ApiListResponse<PersonalityDistributionDto>> {
  if (!campusId) {
    return apiRequest<ApiListResponse<PersonalityDistributionDto>>(`${PERSONALITY_RESULTS_PATH}/distribution`);
  }

  return apiRequest<ApiListResponse<PersonalityDistributionDto>>(
    `${PERSONALITY_RESULTS_PATH}/distribution?${new URLSearchParams({ campusId }).toString()}`,
  );
}

export function getPersonalityCompletion(): Promise<PersonalityCompletionDto> {
  return apiRequest<PersonalityCompletionDto>(`${PERSONALITY_RESULTS_PATH}/completion`);
}
