import { useMutation, useQueryClient } from 'react-query';
import {
  ACCESS_TOKEN_KEY,
  fetchToken,
  FetchTokenDataType,
  FetchTokenReturnType,
  logoutUser,
  REFRESH_TOKEN_KEY
} from '../../api/auth';
import { APIErrorType } from '../../api';
import { CreateIntroducerDataType, IntroducerType } from '../../api/introducer';
import { CreateUserDataType } from '../../api/user';
import { useCreateUserMutation } from './use-user';
import { useCreateIntroducerMutation } from './use-introducer';

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

  function onSuccess({ access, refresh }: { access: string; refresh: string }) {
    localStorage.setItem(ACCESS_TOKEN_KEY, access);
    localStorage.setItem(REFRESH_TOKEN_KEY, refresh);
    return queryClient.invalidateQueries('user');
  }

  return useMutation<FetchTokenReturnType, APIErrorType, FetchTokenDataType>(fetchToken, {
    onSuccess
  });
}

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

  function onSuccess() {
    localStorage.removeItem(ACCESS_TOKEN_KEY);
    localStorage.removeItem(REFRESH_TOKEN_KEY);
    return queryClient.invalidateQueries();
  }

  return useMutation(logoutUser, { onSuccess });
}

export type UseRegisterMutationDataType = CreateUserDataType & CreateIntroducerDataType;

export function useRegisterMutation() {
  const { mutateAsync: createUser } = useCreateUserMutation();
  const { mutateAsync: createIntroducer } = useCreateIntroducerMutation();
  const { mutateAsync: fetchToken } = useLoginMutation();

  async function registerUser(data: UseRegisterMutationDataType) {
    const { iban, ...userData } = data;
    await createUser(userData);
    const introducer = await createIntroducer({ iban });
    const { mobile, password } = userData;
    await fetchToken({ mobile, password });
    return introducer;
  }

  return useMutation<IntroducerType, APIErrorType, UseRegisterMutationDataType>(registerUser);
}
