import VillageApi, { VolunteerInfo } from "@/api/inhert/VillageApi";
import { useSimpleDataLoader } from "@/components/composeabe/loader/SimpleDataLoader";
import { useAuthStore } from "@/store/auth";
import { ref } from "vue";

export function useUserTools() {

  const authStore = useAuthStore();
  const volunteerInfo = ref<VolunteerInfo | null>(null);

  async function getIsVolunteer() {
    if (!authStore.isLogged) {
      return false;
    }
    try {
      volunteerInfo.value = await VillageApi.getVolunteerInfo();
      return volunteerInfo.value !== null;
    } catch (e) {
      console.error(e);
      return false;
    }
  }
  
  const joinedVillagesLoader = useSimpleDataLoader(async () => {
    try {
      return await VillageApi.getClaimedVallageList();
    } catch (error) {
      return [];
    }
  });

  async function getIsJoinedVillage(villageId: number) {
    if (!authStore.isLogged) {
      return false;
    }
    if (!joinedVillagesLoader.isLoaded.value) {
      await joinedVillagesLoader.load();
    }
    try {
      const isJoined = joinedVillagesLoader.content.value?.some(p => p.villageId === villageId) ?? false;
      return isJoined;
    } catch (error) {
      return false;
    }
  }

  return {
    getIsVolunteer,
    getIsJoinedVillage,
    joinedVillagesLoader,
    volunteerInfo,
  };
}