import { ref } from "vue";
import api from "../lib/axios";

export default function useSearchLoads() {
    const loads = ref([]);
    const loading = ref(false);
    const total = ref(0);
    const currentPage = ref(0);

    const getLoadsPublished = async(filterQuery) => {
        loading.value = true;
        let filterArr = Object.values(filterQuery);
        let cleanfilterArr =  filterArr.filter(n=>n);
        var filterStr = "";
        if(cleanfilterArr.length >0){
            filterStr = "?"+cleanfilterArr.join("&");
        }
        try {
            const endpoint = `/v1/loads/find${filterStr}&$sort[createdAt]=-1`;
            console.log(endpoint);
            const {data} = await api.get(endpoint);
            total.value = data.total;
            loads.value = data.data;
        } catch (error) {
            loads.value = [];
            total.value = 0;
        }
        loading.value = false;
    }

    return {
        getLoadsPublished,
        loading,
        loads, 
        total,
        currentPage,
    }
}