<script setup lang="ts" generic="R, E">
import type { UseQueryReturnType } from '@tanstack/vue-query'

type Props = {
  query: UseQueryReturnType<R, E>
}

const slots = defineSlots<{
  default?: (slotBindings: { data: R }) => void
  error?: (slotBindings: { error: E; reload: typeof refetch }) => void
  loading?: () => void
}>()

const { query } = defineProps<Props>()

const { data, error, refetch, isSuccess, isError, isLoading } = query
</script>

<template>
  <slot v-if="isSuccess" name="default" :data="data!" />
  <slot v-else-if="isLoading" name="loading">
    <p class="text-gray-500" v-if="!slots.loading">Загрузка данных...</p>
  </slot>
  <slot v-else-if="isError" name="error" :error="error!" :reload="refetch">
    <template v-if="!slots.error">
      Ошибка загрузки данных:
      {{ error && typeof error === 'object' && 'message' in error ? error.message : error }}
    </template>
  </slot>
</template>
