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

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

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

  return useMutation({
    mutationKey: keys().auth().action("logout").get(),
    mutationFn: logout,

    onSuccess: async (data, variables, context) => {
      queryClient.clear();

      const { success, redirectTo } = data;
      if (success && redirectTo) {
        navigate(redirectTo || "/");
      }
      if (onSuccess) {
        onSuccess(data, variables, context);
      }
    },
    onError: (error, variables, context) => {
      const { message } = error;
      toast({
        title: "Error",
        description: message,
        variant: "destructive",
      });

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