import { ref, computed, watch } from 'vue'
import { defineStore } from 'pinia'
import { api } from 'boot/axios'
import type { Chat } from 'types/Chat'
import { useProjectsStore } from 'stores/projects'
import { useAuthStore } from 'stores/auth'

export const useChatsStore = defineStore('chats', () => {
  const projectsStore = useProjectsStore()
  const chats = ref<Chat[]>([])
  const isInit = ref<boolean>(false)

  const currentProjectId = computed(() => projectsStore.currentProjectId)
  
  async function init () {
    reset()
    const { data } = await api.get('/project/' + currentProjectId.value + '/chat')
    const chatsAPI = data.data
    chats.value.push(...chatsAPI)
    isInit.value = true
  }

  function reset () {
    chats.value = []
    isInit.value = false
  }
  
  async function unlink (chatId: number) {
    const response = await api.get('/project/' + currentProjectId.value + '/chat/' + chatId)
    const chatAPIid = response.data.data.id
    const idx = chats.value.findIndex(item => item.id === chatAPIid)
    chats.value.splice(idx, 1)
  }

  async function getKey () {
    const response = await api.get('/project/' + currentProjectId.value + '/token')
    const key = <string>response.data.data
    return key
  }

  const getChats = computed(() => chats.value)
  
  function chatById (id: number) {
    return chats.value.find(el =>el.id === id)
  }
  
  const authStore = useAuthStore()
  watch(() => authStore.wsEvent, async (event) => {
    if (!event || event.entity !== 'chat' || !event.needUpdateStores.includes('chats')) return
    await init()
  }, { deep: true })

  return {
    chats,
    isInit,
    init,
    reset,
    unlink,
    getKey,
    getChats,
    chatById
  }
})
