import { defineStore } from "pinia";
import { ref } from "vue";
import { createVehicle, deleteVehicle, getVehicles, updateVehicle } from "../services/vehicles";
import { useI18n } from "vue-i18n";
export const useVehiclesStore = defineStore('vehicles', () => {
    
    const vehicles = ref([]);
    const vehiclesTotal = ref(0);
    const vehiclesCurrentPage = ref(0)
    const { t } = useI18n()

    const fetchVehicles = async(filterQuery, reload = false) => {
        let filterArr = Object.values(filterQuery);

        let cleanfilterArr =  filterArr.filter(n=>n);
        var filterStr = "";
        if(cleanfilterArr.length > 0){
            filterStr ="?"+cleanfilterArr.join("&");
        }
        if(vehicles.value.length <= 0 || reload === true) {
            const resp = await getVehicles(filterStr + '&$sort%5BcreatedAt%5D=-1');
            console.log(resp);
            if(resp !== null) {
                vehiclesTotal.value = resp.total;
                vehicles.value = resp.data;
            }
        }
    }

    const createVehicleCompany = async(formData, localData = {}) => {
        const data = await createVehicle(formData);
        if(data) {
            vehicles.value.unshift({
                ...data,
                ...localData
            });
            vehiclesTotal.value++;
            return 'success';
        } else {
            return t('errors.generic');
        }
    }

    const updateVehicleCompany = async(id, formData, localData = {}) => {
        const data = await updateVehicle(id, formData);
        if(data) {
            console.log({data});
            const index = vehicles.value.findIndex((vehicle) => vehicle._id === id);
            vehicles.value[index] = {
                ...vehicles.value[index],
                ...data,
                ...localData
            };

            console.log(vehicles.value[index]);
            return 'success';
        } else {
            return t('errors.generic');
        }
    }

    const deleteVehicleCompany = async(id) => {
        const data = await deleteVehicle(id);
        if(data) {
            vehicles.value = vehicles.value.filter(vehicle => vehicle._id !== id);
            vehiclesTotal.value--;
            return 'success';
        } else {
            return t('errors.generic');
        }
    }

    const clear = () => {
        vehicles.value = [];
        vehiclesTotal.value = 0;
        vehiclesCurrentPage.value = 0;
    }


   return {
        vehicles,
        vehiclesTotal,
        vehiclesCurrentPage,
        fetchVehicles,
        createVehicleCompany,
        updateVehicleCompany,
        deleteVehicleCompany,
        clear
   }
});