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


type RegenerateKeyResponse = {
  apiKey: string;
  createdAt: string;
  lastUsedAt: string;
};

export default function useRegenerateKey() {
  const dispatch = useAppDispatch();
  const queryClient = useQueryClient();
  const { mutateAsync, isPending } = useMutation({
    mutationKey: ["regenerate-key"],
    mutationFn: async () => {
      const res = await apiPost<RegenerateKeyResponse>(
        API_KEYS_ENDPOINTS.API_KEY_CREATE,
        {},
      );
      return res;
    },
    onSuccess: (data) => {
      successToast(SUCCESS_MESSAGES.REGENERATE);
      const { apiKey } = data.data;

      dispatch(
        updateUser({
          apiKey: apiKey,
        }),
      );

      queryClient.invalidateQueries({ queryKey: ["api-keys"] });
    },
    onError: (error: any) => {
      errorToast(error?.response?.data?.message ?? "Something went wrong.");
    },
  });

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