import type { UiMessage } from "@/data/dto/chat";

import type { ChatState } from "./chat-state";

// History pagination size used by the history actors.
export const PAGE_SIZE = 50;

export * from "./chat-message-mappers";
export * from "./chat-send-state";
export * from "./chat-unlock-helpers";

export function applyHistoryLoadedOutput(
  output: {
    messages: UiMessage[];
    hasMore: boolean;
    newOffset: number;
  },
): Pick<
  ChatState,
  "messages" | "hasMore" | "historyOffset" | "historyLoaded"
> {
  return {
    messages: output.messages,
    hasMore: output.hasMore,
    historyOffset: output.newOffset,
    historyLoaded: true,
  };
}

export function applyNetworkHistoryLoadedOutput(
  context: ChatState,
  output: {
    messages: UiMessage[];
    hasMore: boolean;
    newOffset: number;
  },
): Pick<
  ChatState,
  "messages" | "hasMore" | "historyOffset" | "historyLoaded"
> {
  const optimisticTail = context.messages.slice(context.historyOffset);
  return {
    messages: [...output.messages, ...optimisticTail],
    hasMore: output.hasMore,
    historyOffset: output.newOffset,
    historyLoaded: true,
  };
}
