import { defineStore } from 'pinia'

export const useChatStore = defineStore('chat', {
  state: () => ({
    chatList: [],
    selectedChatIndex: 0
  }),

  actions: {
    async loadChats(userId) {
      // Load chats from localStorage on initialization
      const storedChats = localStorage.getItem(`chatHistory-${userId}`)
      if (storedChats) {
        this.chatList = JSON.parse(storedChats)
      } else {
        // Initialize with a default chat if none exists
        this.chatList = [{
          id: 'chat1',
          name: 'New Chat',
          messages: []
        }]
      }
    },

    updateChat(index, chatData) {
      if (index >= 0 && index < this.chatList.length) {
        this.chatList[index] = { ...this.chatList[index], ...chatData }
      }
    },

    addMessage(chatIndex, message) {
      if (chatIndex >= 0 && chatIndex < this.chatList.length) {
        this.chatList[chatIndex].messages.push(message)
      }
    }
  }
})