import { defineStore } from "pinia";
import { ref, computed } from "vue";
import { getUser } from "src/api/user";

export const userStore = defineStore("user", () => {
  const user = ref(null);
  const accessToken = ref(null);

  const isAdministrador = computed(() => user.value?.type?.value === "administrador" || user.value?.type === "administrador");
  const isAssociado = computed(() => user.value?.type?.value === "associado" || user.value?.type === "associado");
  const isParceiro = computed(() => user.value?.type?.value === "parceiro" || user.value?.type === "parceiro");

  const userTipo = computed(() => {
    const t = user.value?.type;
    if (!t) return null;
    return typeof t === "object" ? t.value : t;
  });

  const unreadNotificationsCount = computed(() => user.value?.unread_notifications_count ?? 0);
  const hasUnreadNotifications = computed(() => unreadNotificationsCount.value > 0);

  const setUser = (userData) => {
    user.value = userData;
  };

  const resetUser = () => {
    user.value = null;
    accessToken.value = null;
  };

  const fetchUser = async () => {
    const response = await getUser();
    setUser(response);
  };

  const clearUnreadCount = () => {
    if (user.value) {
      user.value = { ...user.value, unread_notifications_count: 0 };
    }
  };

  return {
    user,
    accessToken,
    isAdministrador,
    isAssociado,
    isParceiro,
    userTipo,
    unreadNotificationsCount,
    hasUnreadNotifications,
    setUser,
    resetUser,
    fetchUser,
    clearUnreadCount,
  };
});
