import { useQuery } from "react-query";
import axios, { AxiosError } from "axios";
import { useDispatch } from "react-redux";
import Cookies from "js-cookie";
import { UserDataRes } from "../../types/UserDataType";
import { updateUserData } from "../Slices/UserSlice";

export const useUserProfile = () => {
  const dispatch = useDispatch();
  const token = Cookies.get("whoxa_web_token");

  return useQuery<UserDataRes, AxiosError>(
    ["users/updateUser"],
    async () => {
      try {
        const response = await axios.post<UserDataRes>(
          `${import.meta.env.VITE_API_URL}users/updateUser`,
          {},
          {
            headers: {
              Authorization: `Bearer ${token}`,
              "x-custom-header": "Web",
            },
          },
        );
        // if account deleted then redirect to login
        if (response.data.data.deleted_at) {
          Cookies.remove("whoxa_web_token");
          sessionStorage.clear();
          localStorage.clear();
          if (window.location.pathname != "/login") {
            window.location.href = "/login";
          }
        }
        // Dispatch user data to Redux
        dispatch(updateUserData(response.data.data));

        return response.data;
      } catch (error) {
        if (axios.isAxiosError(error) && error.response?.status === 401) {
          Cookies.remove("whoxa_web_token");
          localStorage.clear();
          sessionStorage.clear();
          if (window.location.pathname != "/login") {
            window.location.href = "/login";
          }
        }
        throw error; // Important: rethrow so React Query can handle the error state
      }
    },
    {
      staleTime: Infinity,
      cacheTime: Infinity,
    },
  );
};
