import { defineStore } from 'pinia'
import { API } from '@/Api'
import { DEFAULT_CONVERSATION_TITLE } from '@/constants/conversation'

export const useConversationCatalogStore = defineStore('convCatalog', {
  state: () => ({
    conversations: [] as any[],
    loaded: false,
    loading: false,
  }),
  actions: {
    async load(force = false) {
      if (this.loaded && !force) return
      if (this.loading) return
      this.loading = true
      try {
        const { data } = await API.getConversationsMetadata()
        this.conversations = data.conversations
        this.loaded = true
      } finally {
        this.loading = false
      }
    },
    invalidate() {
      this.loaded = false
    },
    addNewConversation(conversationId: string, agentIds: string[] = []) {
      // Check if conversation already exists
      const existingConversation = this.conversations.find((c) => c.id === conversationId)
      if (existingConversation) {
        return // Don't add if it already exists
      }

      // Add a new conversation with default title to the beginning of the list
      const newConversation = {
        id: conversationId,
        title: DEFAULT_CONVERSATION_TITLE,
        lastUpdated: new Date().toISOString(),
        messages: [],
        agentIds: agentIds,
        agentCount: agentIds.length,
      }
      this.conversations.unshift(newConversation)
    },
    updateConversationTitle(conversationId: string, title: string) {
      const conversation = this.conversations.find((c) => c.id === conversationId)
      if (conversation) {
        conversation.title = title
      }
    },
  },
})
