import { createApprovalTaskRequestId } from '../../services/approvalTasks.js'

function normalizeFingerprintValue(value) {
  if (Array.isArray(value)) return value.map(normalizeFingerprintValue)
  if (value && typeof value === 'object') {
    return Object.fromEntries(
      Object.keys(value).sort().map((key) => [key, normalizeFingerprintValue(value[key])])
    )
  }
  return value ?? null
}

export function buildApprovalTaskRetryFingerprint(payload = {}) {
  return JSON.stringify(normalizeFingerprintValue(payload))
}

export function resolveApprovalTaskRetryKey(options = {}) {
  const fingerprint = buildApprovalTaskRetryFingerprint(options.payload)
  const previousFingerprint = String(options.previousFingerprint || '')
  const previousRequestId = String(options.previousRequestId || '')
  return {
    fingerprint,
    requestId: previousRequestId && previousFingerprint === fingerprint
      ? previousRequestId
      : createApprovalTaskRequestId(options.action, options.scopeId)
  }
}
