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

type DestroyCallbackInput = {
  oid: string
  sellerId?: string
  etickets?: Array<{
    id: string
    code?: string
    num: number
    goodsValue?: number
  }>
  reason: string
  eticketType?: string
  ext?: string
  token?: string
}

export async function destroyCallback(
  input: DestroyCallbackInput,
): Promise<{ success: boolean; response?: JsonObject; error?: string }> {
  const bizParams: JsonObject = {
    oid: input.oid,
    reason: input.reason,
  }

  if (input.etickets && input.etickets.length > 0) {
    bizParams.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
    })
  }

  if (input.eticketType) bizParams.eticketType = input.eticketType
  if (input.ext) bizParams.ext = input.ext
  if (input.token) bizParams.token = input.token

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

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

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

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

  if (result.success) {
    logInfo('[kuaishou-industry/destroy-callback]', `销毁回调成功 oid=${input.oid}`, {
      durationMs: result.durationMs,
      response: result.response || null,
    })
  } else if (result.error) {
    logWarn(
      '[kuaishou-industry/destroy-callback]',
      `销毁回调异常 oid=${input.oid}`,
      result.errorDetail || { error: result.error },
    )
  } else {
    logWarn('[kuaishou-industry/destroy-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 } : {}),
  }
}
