import {useEntityManager} from "~/composables/data/useEntityManager";
import ApiResource from "~/models/ApiResource";
import {AssociativeArray, Collection} from "~/types/data";
import {AsyncData} from "#app";

interface useEntityFetchReturnType {
    fetch: (model: typeof ApiResource, id: number) => AsyncData<ApiResource, ApiResource | true>,
    fetchCollection: (model: typeof ApiResource, parent?: ApiResource | null, query?: AssociativeArray) => AsyncData<Collection, any>
}

export const useEntityFetch = (lazy: boolean = false): useEntityFetchReturnType => {
    const { em } = useEntityManager()

    const fetch = (model: typeof ApiResource, id: number) => useAsyncData(
        model.entity + '_' + id,
        () => em.fetch(model, id, true),
        { lazy }
    )

    const fetchCollection = (model: typeof ApiResource, parent: ApiResource | null = null, query: AssociativeArray = []) => useAsyncData(
        model.entity + '_many',
        () => em.fetchCollection(model, parent, query),
        { lazy }
    )

    //@ts-ignore
    return { fetch, fetchCollection }
}
