/** Pinia store for document management — tracks documents per conversation. */

import { defineStore } from 'pinia'
import { ref } from 'vue'
import { documentApi, type IDocumentMeta } from '@/api/documents'

export const useDocumentsStore = defineStore('documents', () => {
  /** Documents keyed by conversation_id */
  const documentsByConversation = ref<Map<string, IDocumentMeta[]>>(new Map())

  /** Loading state per conversation */
  const loadingConversations = ref<Set<string>>(new Set())

  /** Get documents for a conversation (reactive) */
  function getDocuments(conversationId: string): IDocumentMeta[] {
    return documentsByConversation.value.get(conversationId) || []
  }

  /** Fetch documents for a conversation from the server */
  async function fetchDocuments(conversationId: string): Promise<void> {
    if (!conversationId) return
    loadingConversations.value.add(conversationId)
    try {
      const resp = await documentApi.listByConversation(conversationId)
      documentsByConversation.value.set(conversationId, resp.documents || [])
    } catch (e) {
      console.error('Failed to fetch documents:', e)
    } finally {
      loadingConversations.value.delete(conversationId)
    }
  }

  /** Add a document to a conversation (called when Agent creates one) */
  function addDocument(conversationId: string, doc: IDocumentMeta): void {
    const existing = documentsByConversation.value.get(conversationId) || []
    // Prepend (newest first)
    documentsByConversation.value.set(conversationId, [doc, ...existing])
  }

  /** Clear documents for a conversation */
  function clearConversation(conversationId: string): void {
    documentsByConversation.value.delete(conversationId)
  }

  return {
    documentsByConversation,
    loadingConversations,
    getDocuments,
    fetchDocuments,
    addDocument,
    clearConversation,
  }
})
