import { useQueryClient } from "@tanstack/react-query";
import { useNavigate } from "@tanstack/react-router";
import { useLingui } from "@lingui/react/macro";
import { associatePlayer, createPlayer } from "@/features/players/server";
import { playerKeys } from "@/features/players/queries";
import { useServerMutation } from "@/lib/tanstack-query/hooks";

const useCreateUser = () => {
  const navigate = useNavigate();
  const queryClient = useQueryClient();
  const { t } = useLingui();

  return useServerMutation({
    mutationFn: (data: { first_name: string, last_name: string } | string) =>
      typeof data === 'string' ?
        associatePlayer({ data })
      : createPlayer({ data }),
    successMessage: t`Account created successfully!`,
    onSuccess: (data) => {
      queryClient.setQueryData(playerKeys.auth, (old: any) => ({
          ...old,
          user: data
        }));
      navigate({ to: '/' });
    }
  });
};

export default useCreateUser;
