<template>
  <main>
    <div>
      <div v-if="pending">
        Pending...
      </div>
      <div v-else>
        <ul>
          <li v-for="access in accesses">
            Access {{ access.id }}
          </li>
        </ul>
        <div class="ma-3">{{ totalItems }} results</div>
        <a href="#" @click="onClick">Next page</a>
      </div>
    </div>
  </main>
</template>

<script setup lang="ts">
  import type {Ref} from "@vue/reactivity";
  import {computed, ref} from "@vue/reactivity";
  import {useAp2iRequestService} from "~/composables/data/useAp2iRequestService";
  import {useEntityFetch} from "~/composables/data/useEntityFetch";
  import Access from "~/models/Access/Access";
  import {useEntityManager} from "~/composables/data/useEntityManager";

  const { em } = useEntityManager()
  const { apiRequestService } = useAp2iRequestService()

  const page: Ref<number> = ref(1)

  const query = computed(() => {
    return { 'page': page.value }
  })

  // const totalItems: Ref<number> = ref(0)


  const { fetchCollection } = useEntityFetch()

  const { data: collection = [], pending, refresh } = fetchCollection(Access, null, query)

  const accesses = computed(() => {
    // @ts-ignore
    return collection.value ? collection.value.items : []
  })

  const totalItems = computed(() => {
    // @ts-ignore
    return collection.value ? collection.value.totalItems : 0
  })

  // @ts-ignore
  // const { data: accesses = [], pending, refresh } = useLazyAsyncData(
  //     'accesses',
  //     async () => {
  //       const collection = await em.fetchCollection(Access, null, query.value)
  //       totalItems.value = collection.totalItems ?? 0
  //       return collection.items
  //     }
  // )

  const onClick = () => {
    page.value += 1
    refresh()
  }
</script>
