import { type Transaction, getTransactionsHistory } from "@/utils/requests/transactions";
import { LOG } from "@logger";
import { useQuery } from "@tanstack/react-query";
import { useCallback, useMemo, useState } from "react";

const log = LOG.extend("useTransactionsHistory");

const useTransactionsHistory = () => {
	const [referenceFilter, setReferenceFilter] = useState<string>("");

	log.verbose("useTransactionsHistory");

	const { data, isLoading, error, refetch } = useQuery({
		queryKey: ["transactionsHistory"],
		queryFn: getTransactionsHistory,
	});

	const filterByReference = useCallback(
		(reference: string) => {
			if (!data?.length) return [];
			return data.filter((transaction) => transaction.reference.includes(reference));
		},
		[data],
	);
	const transactionsHistory: Transaction[] = useMemo(() => {
		if (!data) return [];
		return filterByReference(referenceFilter);
	}, [data, filterByReference, referenceFilter]);

	return {
		transactionsHistory,
		isLoading,
		error,
		refetch,
		setReferenceFilter,
	};
};

export default useTransactionsHistory;
