import { useMutation, useQueryClient } from "@tanstack/react-query";
import { useAppDispatch } from "../../../useAppRedux";
import { apiPost } from "../../../../lib/api/methods";
import { AUTH_ENDPOINTS } from "../endpoints";
import { successToast } from "../../../../utils/toast";
import { clearUser } from "../../../../store/slices/user";
import { SUCCESS_MESSAGES } from "./messages";


export default function useLogout() {
  const dispatch = useAppDispatch();
  const queryClient = useQueryClient();

  const { mutateAsync, isPending } = useMutation({
    mutationKey: ["logout"],
    mutationFn: async () => {
      const res = await apiPost<{ message: string }>(AUTH_ENDPOINTS.LOGOUT);
      return res;
    },
    onSuccess: () => {
      successToast(SUCCESS_MESSAGES.LOGOUT);
      queryClient.removeQueries();
      dispatch(clearUser());
    },
    onError: () => {
      queryClient.removeQueries();
      dispatch(clearUser());
    },
  });

  return { handleLogout: mutateAsync, loading: isPending };
}
