import { keepPreviousData, useQuery } from "@tanstack/react-query";
import { apiGet } from "../../../lib/api/methods";
import { DASHBOARD_ENDPOINTS } from "./endpoints";
import { PaginationController } from "../../useAppPagination";

export type CreditHistoryRecord = {
  uuid: string;
  type: string;
  source: string;
  credits: number;
  balanceBefore: number;
  balanceAfter: number;
  referenceType: string;
  referenceId: number;
  paymentTransactionId: number;
  remarks: string;
  createdAt: string;
};

type CreditHistoryResponse = Array<CreditHistoryRecord>;

export default function useCreditHistoryFetch(
  pagination: PaginationController,
) {
  const { data, isError, isPending, error } = useQuery({
    queryKey: [
      "credit-history",
      pagination.params.page,
      pagination.params.limit,
      pagination.params.searchQuery,
      pagination.params.sortBy,
      pagination.params.sortDirection,
    ],
    queryFn: async () => {
      const queryParams = {
        limit: pagination.params.limit,
        page: pagination.params.page,
        search: pagination.params.searchQuery,
        sortBy: pagination.params.sortBy,
        sortOrder: pagination?.params?.sortDirection?.toUpperCase(),
      };
      const res = await apiGet<CreditHistoryResponse>(
        DASHBOARD_ENDPOINTS.GET_CREDIT_HISTORY,
        queryParams,
      );
      return {
        creditsHistory: res.data,
        pagination: res.meta,
      };
    },
    staleTime: 60 * 1000,
    placeholderData: keepPreviousData,
    retry: false,
  });

  return {
    data: data,
    loading: isPending,
    isError,
    error,
  };
}
