import { AnyJson } from '~/types/interfaces'
import {FORM_STATUS, QUERY_TYPE} from "~/types/enums";
import {ref, Ref, useFetch} from '@nuxtjs/composition-api'
import DataProvider from "~/services/data/dataProvider";
import {Model} from "@vuex-orm/core";
import {repositoryHelper} from "~/services/store/repository";
import {Store} from "vuex";

/**
 * @category composables/data
 * @param $dataProvider
 * Composable Classe qui va récupérer les Accesses suivant des critères de recherche
 */
export function useDataUtils($dataProvider: DataProvider){

  /**
   * recherche l'item a éditer et alimente le dataprovider
   * @param route
   * @param model
   */
  function getItemToEdit(route: Ref, model: typeof Model){
    const id = parseInt(route.value.params.id)
    if(!id){
      throw new Error('id must be exist')
    }

    const {fetchState} = useFetch(async () => {
      await $dataProvider.invoke({
        type: QUERY_TYPE.MODEL,
        model,
        id
      })
    })
    return {
      fetchState,
      id
    }
  }

  /**
   * Créer l'Item quand l'utilisateur veux créer un nouvel enregistrement
   * @param store
   * @param model
   */
  function createItem(store: Store<any>, model: typeof Model){
    store.commit('form/setFormStatus', FORM_STATUS.CREATE)
    const loading:Ref<Boolean> = ref(true)
    const item: Ref<any> = ref('')
    const create = async (itemToCreate: AnyJson) =>{
      item.value = await repositoryHelper.persist(model, itemToCreate)
      loading.value = false
    }

    return {
      loading,
      create,
      item
    }
  }

  return {
    getItemToEdit,
    createItem
  }
}
