import { useCallback } from 'react';
import {
  chatMessageStoreActions,
  UpdateChatConfigActionArg,
} from '../store/chatMessage';
import { useChatRoomState } from './useChatRoomState';

export type UseChatRoomActionsArg = {
  roomId: string;
};

export function useChatRoomActions({ roomId }: UseChatRoomActionsArg) {
  const { messageListIterator } = useChatRoomState({
    roomId,
  });

  const updateChatConfig = useCallback(
    (arg: UpdateChatConfigActionArg) =>
      chatMessageStoreActions.updateChatConfigAction(arg),
    []
  );

  const loadPrevMessages = useCallback(async () => {
    const res = await messageListIterator();
    chatMessageStoreActions.updatePrevChatMessagesStateAction({
      roomId,
      chatMessages: res.value.messages,
      messageListIterator: res.done ? undefined : messageListIterator,
    });
    return res;
  }, [messageListIterator, roomId]);

  return {
    updateChatConfig,
    loadPrevMessages,
  };
}
