import { useMutation, useQuery, useQueryClient } from 'react-query';

import { useRequiredAuth } from 'src/contexts/JWTContext';
import { clearMood, getCurrentMood } from 'src/services/userMood';
import { type UserMood } from 'src/types/userMood';

export const userMoodKeys = {
  current: (userId: number) => ['user-mood', userId] as const,
};

const isExpired = (mood: UserMood) =>
  new Date(mood.expiresAt).getTime() <= Date.now();

type UseCurrentMoodQueryOptions = {
  /** Skip the request when the consumer knows the feature is off. */
  enabled?: boolean;
};

export const useCurrentMoodQuery = ({
  enabled = true,
}: UseCurrentMoodQueryOptions = {}) => {
  const { user } = useRequiredAuth();
  const userId = user.id;

  return useQuery({
    queryKey: userMoodKeys.current(userId),
    queryFn: () => getCurrentMood(userId),
    enabled,
    // Keep the query pure: surface expired moods as "no mood" instead of
    // deleting them here (a queryFn can run on every background refetch).
    select: response => {
      const mood = response.data;
      return mood && isExpired(mood) ? null : mood;
    },
  });
};

export const useClearMoodMutation = () => {
  const { user } = useRequiredAuth();
  const userId = user.id;
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: () => clearMood(userId),
    onSuccess: () => {
      queryClient.invalidateQueries({
        queryKey: userMoodKeys.current(userId),
      });
    },
  });
};
