import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import type { Conversation, Message } from '../types'
import { chatApi } from '../services/chatApi'

export const useConversationsStore = defineStore('conversations', () => {
  const conversations = ref<Conversation[]>([])
  const currentConversationId = ref<string | null>(null)
  const messages = ref<Message[]>([])
  const loading = ref(false)

  const currentConversation = computed(() =>
    conversations.value.find(c => c.id === currentConversationId.value)
  )

  async function fetchConversations() {
    const { data } = await chatApi.listConversations()
    conversations.value = data
  }

  async function selectConversation(id: string) {
    currentConversationId.value = id
    loading.value = true
    try {
      const { data } = await chatApi.getConversation(id)
      messages.value = data.messages || []
    } finally {
      loading.value = false
    }
  }

  async function createConversation(title?: string) {
    const { data } = await chatApi.createConversation(title)
    conversations.value.unshift(data)
    currentConversationId.value = data.id
    messages.value = []
    return data
  }

  async function deleteConversation(id: string) {
    await chatApi.deleteConversation(id)
    conversations.value = conversations.value.filter(c => c.id !== id)
    if (currentConversationId.value === id) {
      currentConversationId.value = null
      messages.value = []
    }
  }

  function addMessage(message: Message) {
    messages.value.push(message)
  }

  function updateLastAssistantMessage(content: string) {
    const lastMsg = [...messages.value].reverse().find(m => m.role === 'assistant')
    if (lastMsg) {
      lastMsg.content = content
    }
  }

  return {
    conversations, currentConversationId, messages, loading,
    currentConversation,
    fetchConversations, selectConversation, createConversation,
    deleteConversation, addMessage, updateLastAssistantMessage,
  }
})
