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

export const KUAISHOU_INDUSTRY_DESTROYABLE_DISPLAY_STATUS = 'frozen'

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

export type KuaishouIndustryCheckAvailableInput = {
  sellerId?: unknown
  buyerId?: unknown
  orderId?: unknown
  eticketType?: unknown
  bizTypeCode?: unknown
  etickets?: unknown
  eTicketList?: unknown
}

export function checkKuaishouIndustryEticketAvailable(
  input: KuaishouIndustryCheckAvailableInput = {},
) {
  const eticketType = String(input.eticketType || input.bizTypeCode || '').trim()
  const etickets = normalizeAvailableEtickets(input.etickets || input.eTicketList)
  const sellerId = normalizeOpenApiLong(input.sellerId)
  const bizParams = pickDefinedBizParams({
    buyerId: normalizeOpenApiLong(input.buyerId),
    eticketType,
    etickets,
    orderId: normalizeOpenApiLong(input.orderId),
    sellerId,
  })

  return requestKuaishouIndustryOpenApi({
    apiMethod: 'open.virtual.eticket.checkavailable',
    path: '/open/virtual/eticket/checkavailable',
    bizParams,
    ...(sellerId ? { sellerId: String(sellerId) } : {}),
  })
}

export function resolveKuaishouIndustryEticketDisplayStatus(
  response: unknown,
  voucherCode: unknown,
): string {
  const etickets = extractAvailableEtickets(response)
  const normalizedVoucherCode = String(voucherCode || '')
    .trim()
    .toLowerCase()
  const matched = normalizedVoucherCode
    ? etickets.find((eticket) =>
        [eticket.code, eticket.id].some(
          (value) =>
            String(value || '')
              .trim()
              .toLowerCase() === normalizedVoucherCode,
        ),
      )
    : undefined
  const soleEticket = etickets.length === 1 ? etickets[0] : undefined
  const soleEticketHasIdentity = Boolean(String(soleEticket?.code || soleEticket?.id || '').trim())
  const target = matched || (!soleEticketHasIdentity ? soleEticket : undefined)

  return String(target?.displayStatus || target?.status || '')
    .trim()
    .toLowerCase()
}

export function isKuaishouIndustryEticketDestroyableStatus(displayStatus: unknown): boolean {
  return (
    String(displayStatus || '')
      .trim()
      .toLowerCase() === KUAISHOU_INDUSTRY_DESTROYABLE_DISPLAY_STATUS
  )
}

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

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

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

  const current = value as KuaishouIndustryAvailableEticketInput
  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 extractAvailableEtickets(value: unknown): JsonObject[] {
  if (!value || typeof value !== 'object' || Array.isArray(value)) {
    return []
  }

  const current = value as JsonObject
  const data =
    current.data && typeof current.data === 'object' && !Array.isArray(current.data)
      ? (current.data as JsonObject)
      : null
  const candidates = [
    current.etickets,
    current.eTicketList,
    current.eticketList,
    current.list,
    data?.etickets,
    data?.eTicketList,
    data?.eticketList,
    data?.list,
  ]

  for (const candidate of candidates) {
    if (Array.isArray(candidate)) {
      return candidate.filter((item): item is JsonObject =>
        Boolean(item && typeof item === 'object' && !Array.isArray(item)),
      )
    }
  }

  return []
}
