import { apiRequest } from './api.js'

const inflightOcrRequests = new Map()

function buildOcrRequestKey(files = []) {
  return files
    .map((file) => [
      String(file?.name || ''),
      String(file?.size || 0),
      String(file?.lastModified || 0),
      String(file?.receiptId || '')
    ].join(':'))
    .join('|')
}

export function recognizeOcrFiles(files, options = {}) {
  const requestKey = buildOcrRequestKey(files)
  if (requestKey && inflightOcrRequests.has(requestKey)) {
    return inflightOcrRequests.get(requestKey)
  }

  const formData = new FormData()
  for (const file of files) {
    formData.append('files', file)
    formData.append('receipt_ids', String(file?.receiptId || ''))
  }

  const request = apiRequest('/ocr/recognize', {
    method: 'POST',
    body: formData,
    contentType: null,
    ...options
  })
  if (!requestKey) {
    return request
  }

  inflightOcrRequests.set(requestKey, request)
  request.then(
    () => inflightOcrRequests.delete(requestKey),
    () => inflightOcrRequests.delete(requestKey)
  )
  return request
}
