import { useMutation, useQuery, useQueryClient } from 'react-query';
import {
  createUser,
  CreateUserDataType,
  CreateUserReturnType,
  fetchUser,
  UserType
} from '../../api/user';
import { UseQueryResult } from 'react-query/types/react/types';
import { APIErrorType } from '../../api';
import { ACCESS_TOKEN_KEY } from '../../api/auth';

export type useUserReturnType = UseQueryResult<UserType> & { isAuthenticated: boolean };

export function useUser(): useUserReturnType {
  const data = useQuery<UserType, APIErrorType>('user', fetchUser, {
    staleTime: 5 * 60 * 1000,
    retry: false
  });
  return { ...data, isAuthenticated: data.isSuccess };
}

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

  return useMutation<CreateUserReturnType, APIErrorType, CreateUserDataType>(createUser, {
    onSuccess: async ({ token, ...userData }) => {
      localStorage.setItem(ACCESS_TOKEN_KEY, token);
      await queryClient.setQueryData('user', userData);
    }
  });
}
