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

    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);
            console.log(resp.data);
            if(resp !== null) {
                vehicles.value = resp.data;
            }
        }
    }

    const createVehicleCompany = async(formData, localData = {}) => {
        const data = await createVehicle(formData);
        if(data) {
            vehicles.value.push({
                ...data,
                ...localData
            });
            return 'success';
        } else {
            return 'Algo salio mal, intente más tarde';
        }
    }

    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 'Algo salio mal, intente más tarde';
        }
    }

    const deleteVehicleCompany = async(id) => {
        const data = await deleteVehicle(id);
        if(data) {
            vehicles.value = vehicles.value.filter(vehicle => vehicle._id !== id);
            return 'success';
        } else {
            return 'Algo salio mal, intente más tarde';
        }
    }



   return {
        vehicles,
        fetchVehicles,
        createVehicleCompany,
        updateVehicleCompany,
        deleteVehicleCompany
   }
});