import { requestKuaishouIndustryOpenApi } from './openapi-client.js'
import {
  normalizeOpenApiPositiveInteger,
  pickDefinedBizParams,
  type JsonObject,
} from './openapi-values.js'

export type KuaishouIndustryReverseEticketInput = {
  id?: unknown
  code?: unknown
  num?: unknown
}

export type KuaishouIndustryReverseCallbackInput = {
  sellerId?: string
  oid?: unknown
  eticketType?: unknown
  etickets?: unknown
  serialNum?: unknown
  reason?: unknown
  ext?: unknown
  token?: unknown
}

export function reverseKuaishouIndustryCallback(input: KuaishouIndustryReverseCallbackInput = {}) {
  const bizParams = pickDefinedBizParams({
    oid: String(input.oid || '').trim(),
    eticketType: String(input.eticketType || '').trim(),
    etickets: normalizeReverseEtickets(input.etickets),
    serialNum: String(input.serialNum || '').trim(),
    reason: String(input.reason || '').trim(),
    ext: normalizeReverseExt(input.ext),
    token: String(input.token || '').trim(),
  })

  return requestKuaishouIndustryOpenApi({
    apiMethod: 'integration.callback.virtual.eticket.reverse',
    path: '/integration/callback/virtual/eticket/reverse',
    bizParams,
    ...(input.sellerId ? { sellerId: String(input.sellerId).trim() } : {}),
  })
}

function normalizeReverseEtickets(value: unknown): JsonObject[] {
  if (!Array.isArray(value)) {
    return []
  }

  return value
    .map((item) => normalizeReverseEticket(item))
    .filter((item): item is JsonObject => Boolean(item))
}

function normalizeReverseEticket(value: unknown): JsonObject | null {
  if (!value || typeof value !== 'object' || Array.isArray(value)) {
    return null
  }

  const current = value as KuaishouIndustryReverseEticketInput
  const id = String(current.id || '').trim()
  const code = String(current.code || '').trim()
  const num = normalizeOpenApiPositiveInteger(current.num, 1)

  if (!id && !code) {
    return null
  }

  return pickDefinedBizParams({ id, code, num })
}

function normalizeReverseExt(value: unknown): unknown {
  if (!value) {
    return undefined
  }

  if (typeof value === 'string') {
    const text = value.trim()
    return text || undefined
  }

  return value
}
