export const useAvatar = defineStore('avatar', {
  getters: {
    name: () => useUser().user?.name,
    /**
     * Returns the URL of the user's avatar, or null if not available
     */
    src: () => {
      const user = useUser().user
      const fileName = useUser().user?.avatar
      if (user && fileName) {
        const { pb } = usePocketBase()
        return pb.files.getURL(user, fileName, { thumb: '80x80' })
      }
      return null
    }
  },
  actions: {
    /**
     * Uploads an avatar for the current user
     */
    async uploadAvatar(file: File) {
      const { isAuthenticated, userId } = useUser()
      if (isAuthenticated) {
        const { pb } = usePocketBase()
        useUser().user = await pb.collection('users').update(userId!, {
          avatar: file
        })
      } else {
        console.warn('Avatar upload failed: user is not authenticated')
      }
    }
  }
})
