import { ref, computed } from 'vue'
import { defineStore } from 'pinia'
import { api } from 'boot/axios'
import type { Chat, ObsoleteChat } from 'types/Chat'
import { useProjectsStore } from 'stores/projects'
import { useUsersStore } from 'stores/users'

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

  const currentProjectId = computed(() => projectsStore.currentProjectId)
  
  async function init () {
    // guard for double request
    if (isLoading.value) return
    isLoading.value = true
    try {
      reset()
      const chatsResponse = await api.get(`/project/${currentProjectId.value}/chat`)
      chats.value = chatsResponse.data.data
      const obsoleteChatsResponse = await api.get(`/project/${currentProjectId.value}/chat/obsolete`)
      obsoleteChats.value = obsoleteChatsResponse.data.data
      isInit.value = true
    } catch {
      reset()
    } finally {
      isLoading.value = false
    }
  }

  function reset () {
    chats.value = []
    isInit.value = false
  }
  
  async function unlink (chatId: number) {
    const { data } = await api.delete(`/project/${currentProjectId.value}/chat/${chatId}`)
    chats.value = chats.value.filter(item => item.id !== data.data.id)
    const usersStore = useUsersStore()
    reset()
    await init()
    await usersStore.init()
  }

  async function getKey (param?: 'admin') {
    const { data } = await api.get(`/project/${currentProjectId.value}/chat/token` + (param ? '?' + param : ''))
    return <string>data.data.token
  }

  async function shareChat (param?: 'admin') {
    const { data } = await api.get(`/project/${currentProjectId.value}/chat/invite` + (param ? '?' + param : ''))
    return <string>data.data.id
  }
  
  async function update (id: number, newData: Partial<Chat>) {
    const { data } = await api.put(`/project/${currentProjectId.value}/chat/${id}`, newData)
    
    const idx = chats.value.findIndex(item => item.id === id)
    if (chats.value[idx]) Object.assign(chats.value[idx], data.data)
  }
  
  function chatById (id: number) {
    return chats.value.find(el => el.id === id)
  }
 
  return {
    chats,
    obsoleteChats,
    isInit,
    init,
    reset,
    unlink,
    getKey,
    shareChat,
    update,
    chatById
  }
})
