import { defineStore } from 'pinia'
import { useApi } from '@/composables/useApi'
import { useValidationStore } from '@/stores/validation';

export const useCustomerStore = defineStore('customerStore', {

  state: () => ({
    items: [],
    totalItems: 0,
    currentPage: 1,
    rowsPerPage: 30,
    loading: false,
    IsLoadingCard: false,
    error: null,
  }),

  actions: {

    async loadData(page = 1,payload = null) {
      this.IsLoadingCard = true;
      try{
        const { data, error, loading, fetchAll, pagination } = useApi('customers')
        await fetchAll(page,this.rowsPerPage,payload)
        if (data.value) this.items = data.value;
        if (error.value) this.error = error.value;
        this.loading = loading.value;
        this.totalItems = pagination.total;
        this.IsLoadingCard = loading.value;

      }catch(error){
        console.error(error);
        this.IsLoadingCard = false;
      }
    },

    async store(form:any) {
    
        const validationStore = useValidationStore()
    
            validationStore.clearErrors() 
       
            try{
                const { create } = useApi('customers')
                const response = await create(form)
                if (response.status) return response;
                throw response;
    
            }catch(error){
                console.log("validation error");
                validationStore.setErrors(error);
                throw error;
            }
            
      },

      async update(form:any,id:number) {
    
        const validationStore = useValidationStore()
    
            validationStore.clearErrors() 
       
            try{
                const { update } = useApi('customers')
                const response = await update(form,id)
                if (response.status) return response;
                throw response;
            }catch(error){
              console.log(error);
                console.log("validation error");
                validationStore.setErrors(error);
                throw error;
            }
            
      },


    async destroy(id: number) {
      this.loading = true;
        try{
          const { remove } = useApi('customers')
          const response = await remove(id);
          if (response.status) return response;
          throw response;
        }catch(error){
          console.error(error);
        }
        finally{
          this.loading = false;
        }
    },


 


  }
})