import {
  MESSAGE_READ_UNREAD,
  MESSAGE_LINK_MERCHANT_ENTRY
} from '@/constants/message'

/** 未读角标文案（99+ 封顶） */
export function formatMessageBadge(count) {
  const n = Number(count) || 0
  if (n <= 0) return ''
  return n > 99 ? '99+' : String(n)
}

function isUnread(readFlag) {
  return String(readFlag) === MESSAGE_READ_UNREAD
}

/** 是否驳回类消息（用于醒目样式） */
export function isRejectMessage(title) {
  return (title || '').includes('未通过') || (title || '').includes('驳回')
}

/** 列表行 VO → 卡片模型 */
export function mapMessageListRow(row) {
  if (!row) return null
  const title = row.title || ''
  return {
    messageId: row.messageId,
    title,
    summary: row.summary || '',
    readFlag: row.readFlag,
    unread: isUnread(row.readFlag),
    createTime: row.createTime || '',
    bizType: row.bizType || '',
    bizId: row.bizId,
    isReject: isRejectMessage(title)
  }
}

export function mapMessageList(rows) {
  return (rows || []).map(mapMessageListRow).filter(Boolean)
}

/** 详情 VO → 页面模型 */
export function mapMessageDetail(data) {
  if (!data) return null
  const title = data.title || ''
  return {
    messageId: data.messageId,
    title,
    content: data.content || '',
    readFlag: data.readFlag,
    unread: isUnread(data.readFlag),
    createTime: data.createTime || '',
    bizType: data.bizType || '',
    bizId: data.bizId,
    linkType: data.linkType || '',
    linkAvailable: data.linkAvailable !== false,
    isReject: isRejectMessage(title),
    showEntryLink: data.linkType === MESSAGE_LINK_MERCHANT_ENTRY && data.linkAvailable !== false
  }
}
