/**
 * 凭证附件相关业务工具
 */

export const toVoucherKeyList = (value?: string | string[]): string[] => {
  const values = Array.isArray(value) ? value : value?.split(',') || []

  return values.map((key) => key.trim()).filter(Boolean)
}

export const hasVoucherKeys = (value?: string | string[]): boolean =>
  toVoucherKeyList(value).length > 0

export const getErrorMessage = (error: unknown, fallback: string): string => {
  if (!error || typeof error !== 'object') return fallback

  const maybeError = error as {
    msg?: unknown
    message?: unknown
    response?: {
      data?: {
        msg?: unknown
        message?: unknown
      }
    }
  }

  const candidates = [
    maybeError.response?.data?.msg,
    maybeError.response?.data?.message,
    maybeError.msg,
    maybeError.message
  ]

  const message = candidates.find((item): item is string => typeof item === 'string' && !!item)
  return message || fallback
}
