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

type SendCallbackInput = {
  oid: string
  sellerId?: string
  sendType: string
  etickets: Array<{
    id: string
    code?: string
    num: number
    validStartTime: number
    validEndTime: number
    goodsValue?: number
  }>
  sendNum: number
  totalGoodsValue?: number
  token: string
  eticketType?: string
  expressCode?: string
  expressNo?: string
}

export async function sendCallback(
  input: SendCallbackInput,
): Promise<{ success: boolean; response?: JsonObject; error?: string }> {
  const bizParams: JsonObject = {
    oid: input.oid,
    sendType: input.sendType,
    etickets: input.etickets.map((e) => {
      const item: JsonObject = {
        id: e.id,
        num: e.num,
        validStartTime: e.validStartTime,
        validEndTime: e.validEndTime,
      }
      if (e.code) item.code = e.code
      if (e.goodsValue != null) item.goodsValue = e.goodsValue
      return item
    }),
    sendNum: input.sendNum,
    token: input.token,
  }

  if (input.totalGoodsValue != null) bizParams.totalGoodsValue = input.totalGoodsValue
  if (input.eticketType) bizParams.eticketType = input.eticketType
  if (input.expressCode) bizParams.expressCode = input.expressCode
  if (input.expressNo) bizParams.expressNo = input.expressNo

  const result = await requestKuaishouIndustryOpenApi({
    apiMethod: 'integration.callback.virtual.eticket.send',
    path: '/integration/callback/virtual/eticket/send',
    bizParams,
    disableDefaultLog: true,
    ...(input.sellerId ? { sellerId: input.sellerId } : {}),
    onRequest: (request) => {
      const requestLog = {
        sellerId: input.sellerId || '',
        ...request,
      }
      logIntegration(
        '[kuaishou-industry/send-callback]',
        `发起电子凭证发货回调 oid=${input.oid}`,
        requestLog,
      )
    },
  })

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

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

  if (result.skippedReason === 'missing_access_token') {
    const message = 'accessToken 未配置，无法发起发货回调'
    logIntegration('[kuaishou-industry/send-callback]', message, undefined, { level: 'warn' })
    return { success: false, error: message }
  }

  const requestLog = result.request
    ? {
        sellerId: input.sellerId || '',
        ...result.request,
      }
    : undefined

  if (result.success) {
    logIntegration('[kuaishou-industry/send-callback]', `电子凭证发货回调成功 oid=${input.oid}`, {
      durationMs: result.durationMs,
      status: result.httpStatus,
      request: requestLog,
      response: result.response || null,
    })
  } else if (result.error) {
    logIntegration(
      '[kuaishou-industry/send-callback]',
      `电子凭证发货回调异常 oid=${input.oid}`,
      {
        ...(result.errorDetail || { error: result.error }),
        request: requestLog,
      },
      { level: 'warn' },
    )
  } else {
    logIntegration(
      '[kuaishou-industry/send-callback]',
      `电子凭证发货回调失败 oid=${input.oid}`,
      {
        durationMs: result.durationMs,
        status: result.httpStatus,
        request: requestLog,
        response: result.response || null,
      },
      { level: 'warn' },
    )
  }

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