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

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

export function useCurrentPersonalityResultHistory(enabled = true) {
  return useQuery({
    queryKey: PERSONALITY_QUERY_KEYS.history,
    enabled,
    queryFn: async () => {
      const response = await listCurrentPersonalityResultHistory();
      return response.rows
        .map(toPersonalityQuizResultViewModel)
        .filter((result): result is PersonalityQuizResultViewModel => result !== null);
    },
  });
}

export function useSaveCurrentPersonalityResult() {
  const queryClient = useQueryClient();

  return useInvalidatingMutation({
    mutationFn: (submission: PersonalityQuizSubmission) => saveCurrentPersonalityResult(
      toPersonalityQuizResultMutationDto(submission),
    ),
    invalidateQueryKey: PERSONALITY_QUERY_KEYS.distribution,
    onSuccess: async (_data, submission) => {
      await Promise.all([
        queryClient.invalidateQueries({ queryKey: PERSONALITY_QUERY_KEYS.current(submission.quizKind) }),
        queryClient.invalidateQueries({ queryKey: PERSONALITY_QUERY_KEYS.history }),
        queryClient.invalidateQueries({ queryKey: PERSONALITY_QUERY_KEYS.distribution }),
        queryClient.invalidateQueries({ queryKey: PERSONALITY_QUERY_KEYS.completion }),
      ]);
    },
  });
}

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)),
  });
}

export function usePersonalityCompletion(enabled = true) {
  return useQuery({
    queryKey: PERSONALITY_QUERY_KEYS.completion,
    enabled,
    queryFn: getPersonalityCompletion,
  });
}
