import { Message } from '../types'
import { isMessageFromSelf, isNotificationLikeMessage } from './messageTypes'

/** 将接口 / WS 消息转为前端 Message（含 receiver_id 等，供再次提醒等使用） */
export function formatApiMessageToMessage(msg: any, currentUserId: number | null): Message {
  const notificationLike = isNotificationLikeMessage(msg.type, msg.content_type)
  const isSelf = isMessageFromSelf(msg, currentUserId)

  let messageType: 'text' | 'image' | 'file' | 'video' | 'notification' = 'text'
  if (notificationLike) {
    messageType = 'notification'
  } else if (msg.content_type === 'IMAGE') {
    messageType = 'image'
  } else if (msg.content_type === 'VIDEO') {
    messageType = 'video'
  } else if (msg.content_type === 'FILE') {
    messageType = 'file'
  }

  return {
    id: msg.id != null ? msg.id : Date.now(),
    content: msg.content || msg.title || '',
    isSelf,
    type: messageType,
    timestamp: msg.created_at ? new Date(msg.created_at).getTime() : Date.now(),
    title: msg.title,
    actionUrl: msg.action_url,
    actionText: msg.action_text,
    messageType: msg.type,
    content_type: msg.content_type,
    size: msg.size,
    receiver_id: msg.receiver_id,
    sender_id: msg.sender_id,
    app_id: msg.app_id
  }
}
