import type { ChatMessage } from "@/components/chat/ChatMessageCard";
import {
  formatChatDateLabel,
  parseMessageDate,
} from "@/lib/chat/formatMessageTime";

export type MessageGroup =
  | { type: "date"; label: string; key: string }
  | { type: "message"; message: ChatMessage; key: string };

function dayKey(msg: ChatMessage): string {
  const d = parseMessageDate(msg.createdAtIso ?? msg.createdAt);
  if (d) return d.toDateString();
  return "unknown-day";
}

export function groupMessagesByDate(messages: ChatMessage[]): MessageGroup[] {
  const groups: MessageGroup[] = [];
  let lastDay = "";

  messages.forEach((msg, i) => {
    if (!msg) return;

    const dk = dayKey(msg);
    if (dk !== lastDay) {
      lastDay = dk;
      groups.push({
        type: "date",
        label: formatChatDateLabel(msg.createdAtIso ?? msg.createdAt),
        key: `date-${dk}`,
      });
    }
    groups.push({
      type: "message",
      message: msg,
      key: msg._id || `m-${i}`,
    });
  });

  return groups;
}
