import {
  buildFileIdentity,
  MAX_ATTACHMENTS,
  mergeFilesWithLimit
} from '../../views/scripts/travelReimbursementAttachmentModel.js'

export function useWorkbenchAiComposerFiles({
  fileInputRef,
  focusAiModeInput,
  isInputLocked,
  resolveInputLockedMessage = () => '请等待费用测算完成后再继续操作。',
  selectedFiles,
  toast
}) {
  function triggerAiModeFileUpload() {
    if (isInputLocked()) {
      toast(resolveInputLockedMessage() || '请等待当前任务完成后再继续操作。')
      return
    }
    fileInputRef.value?.click()
  }

  function handleAiModeFilesChange(event) {
    const fileMergeResult = mergeFilesWithLimit(selectedFiles.value, Array.from(event.target.files || []), MAX_ATTACHMENTS)
    selectedFiles.value = fileMergeResult.files
    if (fileMergeResult.overflowCount > 0) {
      toast(`一次最多上传 ${MAX_ATTACHMENTS} 份附件，已保留前 ${MAX_ATTACHMENTS} 份。`)
    }
    if (fileInputRef.value) {
      fileInputRef.value.value = ''
    }
    focusAiModeInput()
  }

  function removeAiModeFile(fileKey) {
    selectedFiles.value = selectedFiles.value.filter((file) => buildFileIdentity(file) !== fileKey)
    if (!selectedFiles.value.length && fileInputRef.value) {
      fileInputRef.value.value = ''
    }
    focusAiModeInput()
  }

  function clearAiModeFiles() {
    selectedFiles.value = []
    if (fileInputRef.value) {
      fileInputRef.value.value = ''
    }
  }

  return {
    clearAiModeFiles,
    handleAiModeFilesChange,
    removeAiModeFile,
    triggerAiModeFileUpload
  }
}
