import { logInfo, logWarn } from '../../../utils/logger.js'
import { requestKuaishouIndustryOpenApi, type JsonObject } from './openapi-client.js'

export type ConsumeCallbackInput = {
  oid: string
  sellerId?: string
  etickets: Array<{
    id: string
    code?: string
    num: number
    goodsValue?: number
  }>
  status: string
  consumeType: string
  consumeTime?: number
  storeName?: string
  storeAddress?: string
  expressNo?: string
  expressCode?: string
  appointmentTime?: string
  ext?: string
  token: string
  seriallNum?: string
  consumePoiId?: number
}

export async function consumeCallback(
  input: ConsumeCallbackInput,
): Promise<{ success: boolean; response?: JsonObject; error?: string }> {
  const bizParams = buildConsumeCallbackBizParams(input)

  const result = await requestKuaishouIndustryOpenApi({
    apiMethod: 'integration.callback.virtual.eticket.consume',
    path: '/integration/callback/virtual/eticket/consume',
    bizParams,
    disableDefaultLog: true,
    ...(input.sellerId ? { sellerId: input.sellerId } : {}),
    onRequest: (request) => {
      logInfo('[kuaishou-industry/consume-callback]', `发起核销回调 oid=${input.oid}`, {
        ...request,
        oid: input.oid,
        sellerId: input.sellerId || '',
        status: input.status,
        consumeType: input.consumeType,
      })
    },
  })

  if (result.skippedReason === 'disabled') {
    logInfo('[kuaishou-industry/consume-callback]', '行业电子凭证配置未启用，跳过核销回调')
    return { success: true }
  }

  if (result.skippedReason === 'token_error') {
    const message = result.error || 'accessToken 刷新失败'
    logWarn('[kuaishou-industry/consume-callback]', 'accessToken 刷新失败，无法发起核销回调', {
      error: message,
    })
    return { success: false, error: message }
  }

  if (result.skippedReason === 'missing_access_token') {
    const message = 'accessToken 未配置，无法发起核销回调'
    logWarn('[kuaishou-industry/consume-callback]', message)
    return { success: false, error: message }
  }

  if (result.success) {
    logInfo('[kuaishou-industry/consume-callback]', `核销回调成功 oid=${input.oid}`, {
      durationMs: result.durationMs,
      response: result.response || null,
    })
  } else if (result.error) {
    logWarn(
      '[kuaishou-industry/consume-callback]',
      `核销回调异常 oid=${input.oid}`,
      result.errorDetail || { error: result.error },
    )
  } else {
    logWarn('[kuaishou-industry/consume-callback]', `核销回调失败 oid=${input.oid}`, {
      durationMs: result.durationMs,
      status: result.httpStatus,
      response: result.response || null,
    })
  }

  return {
    success: result.success,
    ...(result.response ? { response: result.response } : {}),
    ...(result.error ? { error: result.error } : {}),
  }
}

export function buildConsumeCallbackBizParams(input: ConsumeCallbackInput): JsonObject {
  const bizParams: JsonObject = {
    oid: input.oid,
    etickets: input.etickets.map((e) => {
      const item: JsonObject = { id: e.id, num: e.num }
      if (e.code) item.code = e.code
      if (e.goodsValue != null) item.goodsValue = e.goodsValue
      return item
    }),
    status: input.status,
    consumeType: input.consumeType,
    token: input.token,
  }

  if (input.consumeTime != null) bizParams.consumeTime = input.consumeTime
  if (input.storeName) bizParams.storeName = input.storeName
  if (input.storeAddress) bizParams.storeAddress = input.storeAddress
  if (input.expressNo) bizParams.expressNo = input.expressNo
  if (input.expressCode) bizParams.expressCode = input.expressCode
  if (input.appointmentTime) bizParams.appointmentTime = input.appointmentTime
  if (input.ext) bizParams.ext = input.ext
  if (input.seriallNum) bizParams.seriallNum = input.seriallNum
  if (input.consumePoiId != null) bizParams.consumePoiId = input.consumePoiId

  return bizParams
}
