import { createRemoteUiMessageIdentity, type UiMessage } from "../ui-message";
import { todayString } from "@/utils/date";

export interface IncomingCommercialMessage {
  messageId: string;
  message: string;
  characterId: string;
  createdAt: string;
}

export function appendCommercialMessage(
  messages: readonly UiMessage[],
  activeCharacterId: string,
  incoming: IncomingCommercialMessage,
): UiMessage[] {
  if (incoming.characterId !== activeCharacterId) return [...messages];
  if (messages.some((message) => message.remoteId === incoming.messageId)) {
    return [...messages];
  }
  const createdAt = new Date(incoming.createdAt);
  return [
    ...messages,
    {
      ...createRemoteUiMessageIdentity(incoming.messageId, true),
      content: incoming.message,
      isFromAI: true,
      date: todayString(Number.isNaN(createdAt.getTime()) ? new Date() : createdAt),
    },
  ];
}
