import { computed, ref, type Ref } from 'vue';
import { ChatMessage } from '../model/Message';
import AgentApi from '@/api/agent/Agent';
import type { ChatSessionManager } from './useChatSession';

/**
 * 聊天记录分页：假定后端 page=1 为最旧一页、page=allPage 为最新一页。
 * 「加载更多」向更早方向取 page-1 并 prepend 到列表顶部。
 */
export function useChatHistoryItemsPager(options: {
  messages: Ref<ChatMessage[]>;
  sessionManager: ChatSessionManager;
  pageSize?: number;
}) {

  const messages = options.messages;
  const sessionManager = options.sessionManager;
  const pageSize = options.pageSize ?? 20;
  const loadingInit = ref(false);
  const loadingMore = ref(false);
  const hasMorePage = ref(false);

  const hasMoreOlder = computed(() => hasMorePage.value && options.sessionManager.currentSessionId.value);
  const historyId = computed(() => options.sessionManager.currentSessionId.value);
  const isLoading = computed(() => loadingInit.value || loadingMore.value);

  let oldestLoadedPage = 0;

  async function init() {
    loadingInit.value = true;
    oldestLoadedPage = 0;
    hasMorePage.value = false;
    messages.value = [];
    try {
      const metaRs = await AgentApi.getChatHistoryItems(1, pageSize, historyId.value);
      const meta = metaRs.requireData();
      if (!meta.allCount || meta.allCount === 0) {
        messages.value = [];
        return;
      }
      const totalPages = Math.max(meta.allPage, 1);
      const pageRes = await AgentApi.getChatHistoryItems(totalPages, pageSize, historyId.value);
      const chunk = pageRes.requireData().items;
      messages.value = chunk.map((it) => ChatMessage.fromHistoryItem(it));
      oldestLoadedPage = totalPages;
      hasMorePage.value = totalPages > 1;
    } finally {
      loadingInit.value = false;
    }
  }

  async function loadOlder() {
    if (
      !historyId.value
      || !hasMoreOlder.value
      || loadingMore.value
      || oldestLoadedPage <= 1
    ) {
      return;
    }
    loadingMore.value = true;
    try {
      const p = oldestLoadedPage - 1;
      const res = await AgentApi.getChatHistoryItems(p, pageSize, historyId.value);
      const chunk = res.requireData().items;
      const prepend = chunk
        .map((it) => ChatMessage.fromHistoryItem(it))
        .filter((it) => {
          //防止在加载之前有新的消息添加，造成分页重复
          return !messages.value.some((m) => m.id === it.id);
        });
      messages.value = [...prepend, ...messages.value];
      oldestLoadedPage = p;
      hasMorePage.value = p > 1;
    } finally {
      loadingMore.value = false;
    }
  }

  function reset() {
    messages.value = [];
    hasMorePage.value = false;
    oldestLoadedPage = 0;
    loadingInit.value = false;
    loadingMore.value = false;
  }

  sessionManager.events.on('pager-reset', () => {
    reset();
  });
  sessionManager.events.on('pager-init', async (id) => {
    await init();
  });

  return {
    messages,
    loadingInit,
    loadingMore,
    isLoading,
    hasMoreOlder,
    init,
    loadOlder,
    reset,
  };
}

export type ChatHistoryItemsPagerManager = ReturnType<typeof useChatHistoryItemsPager>;