import type { ChatMessage } from "@/components/chat/ChatMessageCard";

function matchesPendingServer(server: ChatMessage, pending: ChatMessage): boolean {
  if (String(server.senderId) !== String(pending.senderId)) return false;
  if (pending.fileType !== server.fileType) return false;
  if (pending.fileType === "location" || (!pending.fileType && !pending.file)) {
    return server.content === pending.content;
  }
  return Boolean(pending.fileType && server.fileType === pending.fileType);
}

export function filterResolvedPendingMessages(
  server: ChatMessage[],
  pending: ChatMessage[]
): ChatMessage[] {
  return pending.filter(
    (p) =>
      !server.some((s) => s._id === p._id || matchesPendingServer(s, p))
  );
}

export function dedupeChatMessages(messages: ChatMessage[]): ChatMessage[] {
  const seen = new Set<string>();
  const result: ChatMessage[] = [];

  for (const m of messages) {
    if (!m) continue;
    const idKey =
      m._id && /^[a-f\d]{24}$/i.test(m._id)
        ? m._id
        : `${m.senderId}|${m.content}|${m.file}|${m.createdAt}`;
    if (seen.has(idKey)) continue;
    seen.add(idKey);
    result.push(m);
  }

  return result;
}
