import { defineStore } from 'pinia'
import { ref } from 'vue'

import { chatApi, type Conversation, type ListConversationsParams } from '@/api/chat'
import { useConversationSession } from '@/composables/useConversationSession'

// chat store = 全局 /chat 页那一份会话实例 + 会话列表。
// "单会话消息流"逻辑在 useConversationSession 中（可多实例，详情页内嵌面板自建），
// 这里持有一份并原样转发，保持对外 API 不变（ChatDetailView 零改动）。
export const useChatStore = defineStore('chat', () => {
  const conversations = ref<Conversation[]>([])
  const session = useConversationSession()

  async function loadConversations(filter: ListConversationsParams = {}) {
    conversations.value = await chatApi.listConversations(filter)
  }

  async function deleteConversation(id: string) {
    await chatApi.deleteConversation(id)
    conversations.value = conversations.value.filter((c) => c.id !== id)
    if (session.currentConversation.value?.id === id) {
      session.closeCurrent()
    }
  }

  return {
    conversations,
    currentConversation: session.currentConversation,
    messages: session.messages,
    streamingMessageId: session.streamingMessageId,
    isStreaming: session.isStreaming,
    loadConversations,
    openConversation: session.openConversation,
    loadOlderMessages: session.loadOlderMessages,
    closeCurrent: session.closeCurrent,
    sendMessage: session.sendMessage,
    cancelMessage: session.cancelMessage,
    retryMessage: session.retryMessage,
    deleteConversation,
  }
})
