import { AuthActionResponse, useAuth } from "@/lib/hooks";
import { ILogin_DTO } from "@shared/contexts";
import { UseMutationOptions, useMutation } from "@tanstack/react-query";
import { useNavigate } from "react-router-dom";

import { useToast } from "@/ui/use-toast";
import { useQueryKey } from "../useQueryKey";

export const useLogin = (params?: UseMutationOptions<AuthActionResponse, Error, ILogin_DTO>) => {
  const { toast } = useToast();
  const { onSuccess, onError, ...restParams } = params || {};
  const keys = useQueryKey();
  const { login } = useAuth();
  const navigate = useNavigate();

  return useMutation({
    mutationKey: keys().auth().action("login").get(),
    mutationFn: login,
    onSuccess: (data, variables, context) => {
      const { success, redirectTo } = data;
      if (success && redirectTo) {
        navigate(redirectTo || "/quotes");
      }
      if (onSuccess) {
        onSuccess(data, variables, context);
      }
    },
    onError: (error, variables, context) => {
      const { message } = error;
      console.error(message);

      toast({ description: message, title: "Error" });

      if (onError) {
        onError(error, variables, context);
      }
    },
    ...restParams,
  });
};
