<script setup>
import { computedAsync } from "@vueuse/core";
import { useGraphQlOperation } from "../../composables/graphqlOperation";
import { useApi } from "../../composables/api";
import { buildApiEndpoint } from "../../composables/apiModel";
import { concat } from "lodash-es";
import { ref } from "vue";
const props = defineProps({
  modelName: { type: String, required: true },
  modelBy: { type: Object, required: false },
  itemTitle: { type: [String, Function], required: true },
  fields: { type: Array, required: false },
  cache: { type: [Boolean, Number], required: false, default: false },
  notFoundText: { type: String, required: false },
  placeholder: { type: String, required: false },
  api: { type: Boolean, required: false, default: false }
});
const modelItem = ref({});
const modelItemValue = computedAsync(async () => {
  if (props.modelName && props.itemTitle) {
    let fields = typeof props.itemTitle === "string" ? [props.itemTitle] : [];
    if (props.fields) fields = concat(fields, props.fields);
    const variables = Object.assign({}, props.modelBy);
    let result;
    if (props.api) {
      const api = useApi();
      result = await api.postPromise(buildApiEndpoint(props.modelName), {
        fields,
        variables
      }, void 0, void 0, props.cache);
    } else {
      result = await useGraphQlOperation("Query", props.modelName, fields, variables, props.cache);
    }
    try {
      if (result) {
        modelItem.value = result;
        if (typeof props.itemTitle === "string") return result[props.itemTitle];
        else return props.itemTitle(result);
      }
    } catch (e) {
      console.error(e);
    }
  }
  return props.notFoundText;
}, props.placeholder ?? "");
</script>

<template>
  <slot name="default" :data="modelItem">
    <span>{{ modelItemValue }}</span>
  </slot>
</template>
