import { defineStore } from 'pinia'
import { ref } from 'vue'
import memberApi from '../api/member.api'
import { useLoadable } from '../composables/useLoadable'
import type { Member } from '../lib/interfaces/member.interface'

export const useMemberStore = defineStore('member', () => {
  const members = ref<Member[]>([])
  const { loading, error, withCache, invalidate } = useLoadable()

  async function fetch() {
    await withCache(async () => {
      members.value = await memberApi.index()
    })
  }

  function resolvedAvatarUrl(member: Member): string {
    if (member.imageUrl) return member.imageUrl
    return new URL(`../assets/team/${member.avatarFilename}`, import.meta.url).href
  }

  return { members, loading, error, fetch, resolvedAvatarUrl, invalidate }
})
