import useRequest from "@/lib/app/hooks/useRequest";
import {useEffect, useState} from "react";
import useSWR from "swr";
import {GET_CALLER_HISTORY} from "@/core/data/apiRoutes";

const useCallerHistory = (call_id, phone_number, max_size) => {
    const requestServer = useRequest({auth: true, notification: false});
    const [validData, setValidData] = useState([]);

    //swr config
    const fetcher = (...args) => {
        return requestServer(args, 'get').then(({data}) => {
            return data.data;
        }).catch(() => {
        })
    };

    const {data, isLoading} = useSWR(`${GET_CALLER_HISTORY}?phone_number=${phone_number}&size=${max_size}`, fetcher, {
        revalidateIfStale: false,
        revalidateOnFocus: false,
        revalidateOnReconnect: false,
        keepPreviousData: true
    });

    useEffect(() => {
        data && setValidData(data.filter((item) => item.id != call_id));
    }, [data, call_id]);

    return {
        firstItemOfHistory: validData.length === 0 ? false : validData[0],
        historyList: validData.length < 2 ? false : validData.slice(1),
        isLoadingHistoryList: isLoading,
        errorHistoryList: !data
    }
};

export default useCallerHistory;