/**
 * Message Entity - 消息领域实体
 * 定义消息的核心属性和行为，不依赖任何外部框架
 */

export interface MessageSegment {
  type: 'text' | 'image' | 'mention' | 'reply' | string;
  data: Record<string, any>;
}

export interface Message {
  id: string;
  conversationId: string;
  senderId: string;
  seq: number;
  segments: MessageSegment[];
  createdAt: string;
  status: 'normal' | 'recalled' | 'deleted';
  category?: string;
  sender?: {
    id: string;
    username: string;
    avatar?: string;
    nickname?: string;
  };
}

export interface Conversation {
  id: string;
  type: 'private' | 'group';
  isPinned: boolean;
  lastSeq: number;
  lastMessage?: Message;
  lastMessageAt: string;
  unreadCount: number;
  participants: Array<{
    id: string;
    username: string;
    avatar?: string;
    nickname?: string;
  }>;
  group?: {
    id: string;
    name: string;
    avatar?: string;
  };
  createdAt: string;
  updatedAt: string;
}

export interface UnreadCount {
  total: number;
  system: number;
}

export interface TypingStatus {
  groupId: string;
  userId: string;
  isTyping: boolean;
}

export interface GroupNotice {
  type: 'member_join' | 'member_leave' | 'member_removed' | 'role_changed' | 'muted' | 'unmuted';
  groupId: string;
  data: {
    userId?: string;
    operatorId?: string;
    role?: string;
    username?: string;
    [key: string]: any;
  };
  timestamp: number;
  messageId?: string;
  seq?: number;
}

// 工厂函数
export const createMessage = (data: Partial<Message>): Message => ({
  id: data.id || '',
  conversationId: data.conversationId || '',
  senderId: data.senderId || '',
  seq: data.seq || 0,
  segments: data.segments || [],
  createdAt: data.createdAt || new Date().toISOString(),
  status: data.status || 'normal',
  category: data.category,
  sender: data.sender,
});

export const createConversation = (data: Partial<Conversation>): Conversation => ({
  id: data.id || '',
  type: data.type || 'private',
  isPinned: data.isPinned || false,
  lastSeq: data.lastSeq || 0,
  lastMessage: data.lastMessage,
  lastMessageAt: data.lastMessageAt || new Date().toISOString(),
  unreadCount: data.unreadCount || 0,
  participants: data.participants || [],
  group: data.group,
  createdAt: data.createdAt || new Date().toISOString(),
  updatedAt: data.updatedAt || new Date().toISOString(),
});

// 工具函数
export const isMessageFromCurrentUser = (message: Message, currentUserId: string): boolean => {
  return message.senderId === currentUserId;
};

export const shouldIncrementUnread = (
  message: Message,
  currentUserId: string,
  activeConversationId: string | null
): boolean => {
  return (
    message.senderId !== currentUserId &&
    message.conversationId !== activeConversationId &&
    !!currentUserId
  );
};

export const buildTextContent = (segments: MessageSegment[]): string => {
  return segments
    .filter((s) => s.type === 'text')
    .map((s) => s.data?.text || '')
    .join('');
};

export const buildGroupNoticeText = (notice: GroupNotice): string => {
  const username = notice.data?.username || '用户';
  switch (notice.type) {
    case 'member_join':
      return `"${username}" 加入了群聊`;
    case 'member_leave':
      return `"${username}" 退出了群聊`;
    case 'member_removed':
      return `"${username}" 被移出群聊`;
    case 'muted':
      return `"${username}" 已被管理员禁言`;
    case 'unmuted':
      return `"${username}" 已被管理员解除禁言`;
    default:
      return '';
  }
};
