import { useQuery } from "@tanstack/react-query";
import { apiGet } from "../../../lib/api/methods";
import { DASHBOARD_ENDPOINTS } from "./endpoints";
import { useAppDispatch } from "../../useAppRedux";
import { updateUser } from "../../../store/slices/user";

export type CreditSummary = {
  totalCredits: number;
  creditsSpent: number;
  availableCredits: number;
  lastPurchasedPackage: {
    uuid: string;
    packageName: string;
    credits: number;
    amount: number;
    currency: string;
    purchasedAt: string;
  } | null;
};

export default function useFetchCreditSummary() {
  const dispatch = useAppDispatch();
  const { data, isPending, isError, error } = useQuery({
    queryKey: ["credit-summary"],
    queryFn: async () => {
      const response = await apiGet<CreditSummary>(
        DASHBOARD_ENDPOINTS.GET_WALLET_SUMMARY,
      );

      if (response?.data) {
        dispatch(
          updateUser({
            balance: response.data.availableCredits,
          }),
        );
      }

      return response.data;
    },
    staleTime: 30 * 1000,
    refetchOnWindowFocus: true,
  });

  return {
    creditSummary: data,
    loading: isPending,
    error: isError ? error : null,
  };
}
