import { runtimeConfig } from '../../config/runtime.js'

import { DEFAULT_REDEEM_PROOF_MODE, type RedeemProofMode } from './session-proof-constants.js'

type RedeemResultForProof = {
  classification?: {
    success?: boolean
  }
  redeem?: {
    iRet?: number | string
    ret?: number | string
  }
} | null | undefined

export function resolveRedeemProofMode(rawMode: unknown = runtimeConfig.redeem.proofMode): RedeemProofMode {
  const normalized = String(rawMode || '')
    .trim()
    .toLowerCase()

  if (normalized === 'basic' || normalized === 'off') {
    return normalized
  }

  return DEFAULT_REDEEM_PROOF_MODE
}

export function shouldCaptureBeijingTimeProof(finalResult: RedeemResultForProof): boolean {
  if (finalResult?.classification?.success === true) {
    return true
  }

  if (finalResult?.classification?.success === false) {
    return false
  }

  const retCode = Number(finalResult?.redeem?.iRet ?? finalResult?.redeem?.ret)
  return Number.isFinite(retCode) && retCode === 0
}
