import { normalizeOperationFeedbackContext } from '../../composables/useOperationFeedback.js'

export function useTravelReimbursementCreateViewOperationFeedback({
  activeSessionType,
  conversationId,
  currentUser,
  props,
  resolveCurrentUserId
}) {
  const promptedOperationFeedbackRunIds = new Set()

  function emitOperationCompleted(payload = {}, extras = {}) {
    const runId = String(payload?.run_id || payload?.runId || '').trim()
    const operationStatus = String(payload?.status || '').trim()
    if (!runId || promptedOperationFeedbackRunIds.has(runId) || operationStatus !== 'succeeded') {
      return null
    }
    const result = payload?.result && typeof payload.result === 'object' ? payload.result : {}
    promptedOperationFeedbackRunIds.add(runId)
    return normalizeOperationFeedbackContext({
      run_id: runId,
      conversation_id: String(payload?.conversation_id || payload?.conversationId || conversationId.value || '').trim(),
      user_id: resolveCurrentUserId(),
      selected_agent: String(payload?.selected_agent || payload?.selectedAgent || '').trim(),
      source: 'user_message',
      session_type: activeSessionType.value,
      operation_type: String(extras.operationType || 'assistant_round').trim(),
      operation_status: operationStatus,
      status: operationStatus,
      route_reason: String(payload?.route_reason || payload?.routeReason || '').trim(),
      entry_source: props.entrySource,
      trace_summary: payload?.trace_summary || payload?.traceSummary || null,
      result_summary: String(result.answer || result.message || '').trim()
    }, currentUser.value || {})
  }

  return {
    emitOperationCompleted
  }
}
