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

export const useUsersStore = defineStore('users', () => {
  const projectsStore = useProjectsStore()
  const users = ref<User[]>([])
  const isInit = ref<boolean>(false)

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

  function reset () {
    users.value = []
    isInit.value = false
  }
  
  async function update (userId: number, userData: UserParams) {
    const { data } = await api.put('/project/' + currentProjectId.value + '/user/' + userId, userData)
    console.log('update', data.data)
    const userAPI = data.data
    const idx = users.value.findIndex(item => item.id === userAPI.id)
    if (users.value[idx]) Object.assign(users.value[idx], userAPI)
  }

  async function blockUser (userId: number) {
    const { data } = await api.put('/project/' + currentProjectId.value + '/user/' + userId, { is_blocked: true })
    const userAPI = data.data
    const idx = users.value.findIndex(item => item.id === userAPI.id)
    if (users.value[idx]) Object.assign(users.value[idx], userAPI)
  }

  async function unblockUser (userId: number) {
    const { data } = await api.put('/project/' + currentProjectId.value + '/user/' + userId, { is_blocked: false })
    const userAPI = data.data
    const idx = users.value.findIndex(item => item.id === userAPI.id)
    if (users.value[idx]) Object.assign(users.value[idx], userAPI)
  }

  function userById (id: number) {
    return users.value.find(el =>el.id === id)
  }

  function userNameById (id: number) {
    const user = userById(id)
    return user?.fullname 
    || [user?.firstname, user?.lastname].filter(Boolean).join(' ').trim() 
    || user?.username 
    || '---'
  }

  const getUsers = computed(() => users.value)

  const authStore = useAuthStore()
  watch(() => authStore.wsEvent, async (event) => {
    if (!event || event.entity !== 'user' || !event.needUpdateStores.includes('users')) return
    await init()
  }, { deep: true })

  return {
    users,
    isInit,
    init,
    reset,
    update,
    blockUser,
    unblockUser,
    userById,
    userNameById,
    getUsers
  }
})
