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)

  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) return

    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'
    }
  }

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

  onUnmounted(revokeBlobUrl)

  return { documentUrl, documentError, refreshUrl }
}
