import { buildUnsavedDraftAttachmentConfirmationMessage } from './travelReimbursementAttachmentModel.js'
import { REIMBURSEMENT_LIST_PREVIEW_PARAMS } from '../../services/reimbursements.js'

export async function handleDraftAssociationPreflight({
  activeReviewPayload,
  adjustComposerTextareaHeight,
  buildComposerFilePreviews,
  buildDraftAssociationQueryPayload,
  createPendingAttachmentAssociationId,
  composerBusinessTimeDraftTouched,
  composerBusinessTimeTags,
  composerDraft,
  createMessage,
  detailScopedClaimId,
  draftClaimId,
  effectiveIsKnowledgeSession,
  extraContext,
  fetchExpenseClaims,
  fileNames,
  files,
  messages,
  nextTick,
  options,
  pendingAttachmentAssociations,
  persistSessionState,
  resetFlowRun,
  resolvedUploadDisposition,
  reviewAction,
  scrollToBottom,
  stewardDelegated,
  toast,
  userText
}) {
      const hasUnsavedReviewDraft = Boolean(
        !stewardDelegated &&
        !effectiveIsKnowledgeSession &&
        files.length &&
        activeReviewPayload.value &&
        !String(draftClaimId.value || '').trim() &&
        !detailScopedClaimId &&
        !resolvedUploadDisposition &&
        !options.skipDraftAssociationPrompt &&
        !reviewAction
      )
      if (hasUnsavedReviewDraft) {
        const associationId = createPendingAttachmentAssociationId()
        pendingAttachmentAssociations.set(associationId, {
          files,
          fileNames,
          filePreviews: buildComposerFilePreviews(files),
          extraContext
        })
        resetFlowRun()
        if (!options.skipUserMessage) {
          messages.value.push(createMessage('user', userText, fileNames))
        }
        messages.value.push(createMessage(
          'assistant',
          buildUnsavedDraftAttachmentConfirmationMessage({ fileNames }),
          [],
          {
            meta: ['等待确认保存并归集'],
            pendingAttachmentAssociation: {
              id: associationId,
              mode: 'save_then_associate',
              status: 'pending',
              fileNames
            }
          }
        ))
        nextTick(scrollToBottom)
        persistSessionState()
        return { handled: true, value: null }
      }

      if (
        !stewardDelegated &&
        !effectiveIsKnowledgeSession &&
        files.length &&
        !resolvedUploadDisposition &&
        !options.skipDraftAssociationPrompt &&
        !reviewAction
      ) {
        try {
          const claims = await fetchExpenseClaims(REIMBURSEMENT_LIST_PREVIEW_PARAMS)
          const queryPayload = buildDraftAssociationQueryPayload(claims)
          if (queryPayload?.records?.length) {
            resetFlowRun()
            if (!options.skipUserMessage) {
              messages.value.push(createMessage('user', userText, fileNames))
            }
            messages.value.push(createMessage(
              'assistant',
              `我找到 ${queryPayload.records.length} 张可关联的草稿/待补单据。请先选择这批附件要归集到哪张单据，我再开始识别附件。`,
              [],
              {
                meta: ['等待选择关联单据'],
                queryPayload
              }
            ))
            composerDraft.value = ''
            composerBusinessTimeTags.value = []
            composerBusinessTimeDraftTouched.value = false
            nextTick(() => {
              adjustComposerTextareaHeight()
              scrollToBottom()
            })
            persistSessionState()
            return { handled: true, value: null }
          }
        } catch (error) {
          console.warn('Failed to load draft claims before attachment recognition:', error)
          resetFlowRun()
          if (!options.skipUserMessage) {
            messages.value.push(createMessage('user', userText, fileNames))
          }
          messages.value.push(createMessage(
            'assistant',
            '我暂时没能查询到可关联的草稿/待补单据，所以先不识别这批附件。请稍后重试，或从对应草稿进入后继续上传票据。',
            [],
            {
              meta: ['单据查询失败']
            }
          ))
          nextTick(scrollToBottom)
          persistSessionState()
          toast(error?.message || '查询可关联草稿失败，请稍后重试。')
          return { handled: true, value: null }
        }
      }

  return { handled: false, value: null }
}
