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

function buildStatusQuery(status = 'all') {
  const normalized = String(status || 'all').trim()
  return normalized ? `?status=${encodeURIComponent(normalized)}` : ''
}

export function fetchReceiptFolderItems(status = 'all') {
  return apiRequest(`/receipt-folder${buildStatusQuery(status)}`)
}

export function fetchReceiptFolderDetail(receiptId) {
  return apiRequest(`/receipt-folder/${encodeURIComponent(String(receiptId || '').trim())}`)
}

export function updateReceiptFolderItem(receiptId, payload = {}) {
  return apiRequest(`/receipt-folder/${encodeURIComponent(String(receiptId || '').trim())}`, {
    method: 'PATCH',
    body: JSON.stringify(payload)
  })
}

export function deleteReceiptFolderItem(receiptId) {
  return apiRequest(`/receipt-folder/${encodeURIComponent(String(receiptId || '').trim())}`, {
    method: 'DELETE'
  })
}

export function fetchReceiptFolderAsset(pathOrUrl) {
  const target = String(pathOrUrl || '').trim()
  if (!target) {
    throw new Error('票据文件地址为空。')
  }
  return apiRequest(target, {
    cache: 'no-store',
    responseType: 'blob'
  })
}

export async function buildReceiptFile(receipt) {
  const blob = await fetchReceiptFolderAsset(receipt?.source_url || receipt?.sourceUrl)
  const fileName = String(receipt?.file_name || receipt?.fileName || 'receipt.bin').trim() || 'receipt.bin'
  const mediaType = String(receipt?.media_type || receipt?.mediaType || blob.type || 'application/octet-stream')
  const file = new File([blob], fileName, { type: mediaType })
  Object.defineProperty(file, 'receiptId', {
    value: String(receipt?.id || ''),
    enumerable: false
  })
  return file
}
