let pendingRequest = null;

export const useAuth = () => {
  const memberData = useState("auth.member", () => null);

  const isAuthenticated = computed(() => !!memberData.value);

  const isMember = computed(() => !!memberData.value);

  const checkMemberStatus = async () => {
    if (pendingRequest) {
      return pendingRequest;
    }

    pendingRequest = (async () => {
      try {
        const response = await $fetch("/api/auth/member");
        memberData.value = response;
        return true;
      } catch (error) {
        memberData.value = null;
        return false;
      } finally {
        pendingRequest = null;
      }
    })();

    return pendingRequest;
  };

  const logout = async () => {
    try {
      await $fetch("/api/auth/logout", {
        method: "POST",
      });
      memberData.value = null;
      await navigateTo("/");
    } catch (error) {
      console.error("Logout failed:", error);
    }
  };

  return {
    isAuthenticated: readonly(isAuthenticated),
    isMember: readonly(isMember),
    memberData: readonly(memberData),
    checkMemberStatus,
    fetchMember: checkMemberStatus, // Alias for consistency
    logout,
  };
};
