import { defineStore } from "pinia";
import { ref } from "vue";
import { getBudgets,  getCompany, updateBudget, updateCompany, deleteBudget, createBudget, getUsers } from "../services/company";
import api from "../lib/axios";

export const useCompanyStore = defineStore('company', () => {

    const company = ref(null)
    const users = ref([]);
    const budgets = ref([]);
    const proposals = ref([])
    const loading = ref(false);

    const getCompanyData = async() => {
        const companyId = localStorage.getItem('id');
        loading.value = true;
        if(!company.value) {
            loading.value = true;
            const resp = await getCompany(companyId);
            console.log(resp);
            company.value = resp;
        }
        loading.value = false;
    }

    const getUsersCompany = async() => {
        const companyId = localStorage.getItem('id');
        if(users.value.length <= 0) {
            const resp = await getUsers(companyId);
            console.log(resp);
            if(resp !== null && resp.total > 0) {
                users.value = resp.data;
            } else {
                users.value = [];
            }
        }
    }

    const editCompany = async(formData) => {
        const data = await updateCompany(company.value._id, formData);
        if(data === null) {
            return 'Algo salio mal, intente más tarde';
        } else {
            company.value = {
                ...company.value,
                ...formData,
            };

            return 'success';
        }
    }

    const clear = () => {
        company.value = null;
        // companyid = null;
        loading.value = false;
    }

    const $reset = () => {
        company.value = null;
        // companyid = null;
        loading.value = false;
    }


    ///loads?company=64fa70c130d2650011ac4f3a&status[$ne]=Closed,posted_by_name[$regex]=ju&posted_by_name[$options]=i

    const getProposalsCompany = async() => {
        const companyId = localStorage.getItem('id');
        try {
            const endpoint = `/proposals?carrier=${companyId}`;
            const {data} = await api.get(endpoint);
            proposals.value = data.data;
            console.log(data);
        } catch (error) {
            proposals.value = [];
            console.log(error);
        }
    }

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

        let cleanfilterArr =  filterArr.filter(n=>n);
        // console.log(cleanfilterArr);
        var filterStr = "";
        if(cleanfilterArr.length >0){
            filterStr ="?"+cleanfilterArr.join("&");
        }

        if(budgets.value.length <= 0 || reload === true) {
            try {
                const data = await getBudgets(filterStr);
                if(data.total > 0) {
                    budgets.value = data.data;
                } else {
                    budgets.value = [];
                }
            } catch (error) {
                budgets.value = [];
            }
        }
    }

    const updateBudgetCompany = async(id, formData) => {
        try {
            const data = await updateBudget(id, formData);
            console.log(data);
            if(data) {
                const index = budgets.value.findIndex((budget) => budget._id === id);
                budgets.value[index] = {
                    ...budgets.value[index],
                    ...data,
                    material: udgets.value[index].material
                };
                return data;
            } else {
                return null;
            }
        } catch (error) {
            return null;
        }
    } 

    const createBudgetCompany = async(formData) => {
        try {
            const data = await createBudget(formData);
            console.log(data);
            if(data) {
                budgets.value.push(data);
                return data;
            } else {
                return null;
            }
        } catch (error) {
            return null;
        }
    } 

    const deleteBudgetCompany = async(id) => {
        try {
            const data = await deleteBudget(id);
            console.log(data);
            if(data) {
                budgets.value = budgets.value.filter(budget => budget._id !== id);
                return data;
            } else {
                return null;
            }
        } catch (error) {
            return null;
        }
    } 


   return {
       getCompanyData,
       getProposalsCompany,
       getBudgetsCompany,
       getUsersCompany,
       editCompany,
       updateBudgetCompany,
       createBudgetCompany,
       deleteBudgetCompany,
       budgets,
       users,
       clear,
       $reset,
       loading,
       proposals,
       company,
   }
});