import { parseJsonObject } from '../../utils/json.js'

type JsonObject = Record<string, unknown>

export function extractAgisoTradePayload(body: unknown): JsonObject {
  const normalizedBody = normalizeRecord(body)
  const rawJson = String(normalizedBody.json || normalizedBody.JSON || '').trim()

  if (rawJson) {
    return normalizeRecord(parseJsonObject(rawJson, { preserveLargeIntegers: true }))
  }

  return normalizedBody
}

export function resolveAgisoTradePlatformOrderId(payload: unknown): string {
  const normalizedPayload = normalizeRecord(payload)
  const firstItem = extractAgisoTradeOrderItemSources(normalizedPayload)[0] || {}

  return pickFirstNonEmpty([
    normalizedPayload.biz_order_id,
    normalizedPayload.Tid,
    normalizedPayload.tid,
    normalizedPayload.Oid,
    normalizedPayload.oid,
    normalizedPayload.order_id,
    normalizedPayload.orderId,
    firstItem.Oid,
    firstItem.oid,
  ])
}

export function extractAgisoTradeOrderItemSources(payload: unknown): JsonObject[] {
  const normalizedPayload = normalizeRecord(payload)
  const candidates = [
    normalizedPayload.items,
    normalizedPayload.Items,
    normalizedPayload.orders,
    normalizedPayload.Orders,
    normalizedPayload.order_list,
    normalizedPayload.OrderList,
  ]

  for (const current of candidates) {
    if (Array.isArray(current) && current.length > 0) {
      return current.map((item) => normalizeRecord(item)).filter((item) => Object.keys(item).length > 0)
    }
  }

  if (Object.keys(normalizedPayload).length > 0) {
    return [normalizedPayload]
  }

  return []
}

function normalizeRecord(value: unknown): JsonObject {
  return value && typeof value === 'object' && !Array.isArray(value) ? value as JsonObject : {}
}

function pickFirstNonEmpty(values: unknown[]): string {
  for (const value of values) {
    if (typeof value === 'string' && value.trim()) {
      return value.trim()
    }

    if (typeof value === 'number' && Number.isFinite(value)) {
      return String(value)
    }
  }

  return ''
}
