import {useEffect, useState} from "react"
import { useTariffStore } from "@root/stores/tariffs";
import {getRecentlyPurchasedTariffs} from "@root/api/recentlyPurchasedTariffs"

export const useRecentlyPurchasedTariffs = () => {
	const [recentlyPurchased, setRecentlyPurchased] = useState<any>([])
	const tariffs = useTariffStore((state) => state.tariffs);
	useEffect(() => {
		async function fetchData() {
			try {
				const [response, errorMsg] = await getRecentlyPurchasedTariffs();
				if (errorMsg) {
					console.error("Произошла ошибка при вызове getRecentlyPurchasedTariffs:", errorMsg);
				}
				if (response) {
					const recentlyTariffs = response.slice(0, 10).map((obj: { id: string })=>obj.id)
					setRecentlyPurchased(tariffs.filter((tariffs)=>{
						return recentlyTariffs.includes(tariffs._id)}));
				}
			} catch (err) {
				console.error("Произошла ошибка при вызове getRecentlyPurchasedTariffs:", err);
			}
		}

		fetchData();
	}, [tariffs]);

	return {recentlyPurchased}
}
