import { buildSuggestedActionKey } from '../../utils/suggestedActionKey.js'
import { normalizeApplicationPreview } from '../../utils/expenseApplicationPreview.js'

export function useTravelReimbursementCreateViewSuggestedActionLock({
  messages,
  persistSessionState,
  resolveApplicationPreviewRows
}) {
  function lockSuggestedActionMessage(message, action) {
    const messageId = String(message?.id || '').trim()
    const targetMessage = messages.value.find((item) => String(item.id || '') === messageId) || message
    if (!targetMessage || targetMessage.suggestedActionsLocked) {
      return false
    }

    const actionPayload = action?.payload && typeof action.payload === 'object' ? action.payload : {}
    const selectedLabel = String(action?.label || actionPayload.expense_type_label || '').trim()
    const nextMeta = Array.isArray(targetMessage.meta)
      ? targetMessage.meta.filter((item) => item !== '等待选择场景')
      : []
    const selectedMeta = selectedLabel ? `已选择${selectedLabel}` : '已选择场景'

    targetMessage.suggestedActionsLocked = true
    targetMessage.selectedSuggestedActionKey = buildSuggestedActionKey(action)
    targetMessage.selectedSuggestedActionLabel = selectedLabel
    targetMessage.meta = Array.from(new Set([...nextMeta, selectedMeta]))
    persistSessionState()
    return true
  }

  function buildMessageActionRows(message) {
    const applicationPreview = message?.applicationPreview
      ? normalizeApplicationPreview(message.applicationPreview)
      : null
    if (!applicationPreview?.fields) {
      return []
    }
    return resolveApplicationPreviewRows({ applicationPreview }).map((row) =>
      `${row.label}：${row.value || '待补充'}`
    )
  }

  return {
    buildMessageActionRows,
    lockSuggestedActionMessage
  }
}
