import type { AsyncData } from '#app'
import { v4 as uuid4 } from 'uuid'
import type { Ref } from 'vue'
import { useImageManager } from '~/composables/data/useImageManager'

interface useImageFetchReturnType {
  fetch: (
    id: Ref<number | null>,
    defaultImage?: string | null,
    height?: number,
    width?: number,
  ) => AsyncData<string | ArrayBuffer | null, Error | null>
}

/**
 * Sert d'intermédiaire entre les composants et l'ImageManager en fournissant une méthode useAsyncData toute prête.
 */
export const useImageFetch = (): useImageFetchReturnType => {
  const { imageManager } = useImageManager()

  const fetch = (
    id: Ref<number | null>, // If id is null, fetch shall return the default image url
    defaultImage: string | null = null,
    height: number = 0,
    width: number = 0,
  ) =>
    useAsyncData(
      'img' + (id ?? defaultImage ?? 0) + '_' + uuid4(),
      () => imageManager.get(id.value, defaultImage, height, width),
      { lazy: true, server: false }, // Always fetch images client-side
    )

  return { fetch }
}
