<!-- Permet de requêter une subResource et de donner son contenu à un slot -->

<template>
  <main>
    <v-skeleton-loader v-if="pending" :type="loaderType" />
    <div v-else>
      <!-- Content -->
      <slot name="list.item" v-bind="{ items }" />

      <!-- New button -->
      <v-btn v-if="newLink" class="theme-primary float-right">
        <NuxtLink :to="newLink" class="no-decoration">
          <v-icon>fa-plus-circle</v-icon>
          <span>{{ $t('add') }}</span>
        </NuxtLink>
      </v-btn>
    </div>
    <slot />
  </main>
</template>

<script setup lang="ts">
import { computed, toRefs } from '@vue/reactivity'
import type { ComputedRef, ToRefs } from '@vue/reactivity'
import { useEntityFetch } from '~/composables/data/useEntityFetch'
import type { Collection } from '~/types/data'

const props = defineProps({
  model: {
    type: Object,
    required: true,
  },
  parent: {
    type: Object,
    required: false,
  },
  loaderType: {
    type: String,
    required: false,
    default: 'text',
  },
  newLink: {
    type: String,
    required: false,
  },
})

const { model, parent }: ToRefs = toRefs(props)

const { fetchCollection } = useEntityFetch()

const { data: collection, pending } = await fetchCollection(
  model.value,
  parent.value,
)

const items: ComputedRef<Collection> = computed(
  () => collection.value ?? { items: [], pagination: {}, totalItems: 0 },
)
</script>
