import { useQuery } from '@tanstack/react-query';
import {
  getCurrentPersonalityResult,
  listPersonalityDistribution,
  saveCurrentPersonalityResult,
} from '@/shared/api/personality';
import {
  toPersonalityQuizResultMutationDto,
  toPersonalityQuizResultViewModel,
} from '@/business/personality/mappers';
import type { PersonalityQuizSubmission } from '@/business/personality/types';
import { PERSONALITY_QUERY_KEYS } from '@/shared/constants/personality';
import { getApiListRows } from '@/shared/business/apiListRows';
import { useInvalidatingMutation } from '@/shared/business/queryMutations';

export function useCurrentPersonalityResult() {
  return useQuery({
    queryKey: PERSONALITY_QUERY_KEYS.current,
    queryFn: async () => {
      const response = await getCurrentPersonalityResult();
      return toPersonalityQuizResultViewModel(response);
    },
  });
}

export function useSaveCurrentPersonalityResult() {
  return useInvalidatingMutation({
    mutationFn: (submission: PersonalityQuizSubmission) => saveCurrentPersonalityResult(
      toPersonalityQuizResultMutationDto(submission),
    ),
    invalidateQueryKeys: [
      PERSONALITY_QUERY_KEYS.current,
      PERSONALITY_QUERY_KEYS.distribution,
    ],
  });
}

export function usePersonalityDistribution(campusId?: string, enabled = true) {
  return useQuery({
    queryKey: campusId ? [...PERSONALITY_QUERY_KEYS.distribution, campusId] : PERSONALITY_QUERY_KEYS.distribution,
    enabled,
    queryFn: () => getApiListRows(listPersonalityDistribution(campusId)),
  });
}
