import { ref, watch, onUnmounted, type Ref } from 'vue'
import { getBlob } from '../api/client'
import { useBatchStore } from '../stores/batches'

export function usePresignedUrl(batchId: Ref<string | undefined>) {
  const batchStore = useBatchStore()
  const documentUrl = ref<string | null>(null)
  const documentError = ref<string | null>(null)
  const documentLoading = ref(false)

  let currentBlobUrl: string | null = null

  function revokeBlobUrl(): void {
    if (currentBlobUrl) {
      URL.revokeObjectURL(currentBlobUrl)
      currentBlobUrl = null
    }
  }

  async function refreshUrl(): Promise<void> {
    revokeBlobUrl()
    documentUrl.value = null
    documentError.value = null

    if (!batchId.value) {
      documentLoading.value = false
      return
    }

    documentLoading.value = true
    try {
      await batchStore.getBatch(batchId.value)
      const blob = await getBlob(`digitization-batches/${batchId.value}/document`)
      if (!blob.size) {
        throw new Error('Document is empty')
      }
      currentBlobUrl = URL.createObjectURL(blob)
      documentUrl.value = currentBlobUrl
    } catch (e: unknown) {
      documentError.value = e instanceof Error ? e.message : 'Failed to load document'
    } finally {
      documentLoading.value = false
    }
  }

  watch(
    batchId,
    async (id) => {
      if (id) {
        await refreshUrl()
      } else {
        revokeBlobUrl()
        documentUrl.value = null
        documentError.value = null
        documentLoading.value = false
      }
    },
    { immediate: true }
  )

  onUnmounted(revokeBlobUrl)

  return { documentUrl, documentError, documentLoading, refreshUrl }
}
