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

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

  const normalizeUser = (userData) => {
    if (!userData) return null;

    return {
      ...userData,
      client: userData.client ?? (userData.client_id ? {
        id: userData.client_id,
        document: userData.client_document ?? null,
      } : null),
      provider: userData.provider ?? (userData.provider_id ? {
        id: userData.provider_id,
      } : null),
    };
  };

  const setUser = (userData) => {
    const normalized = normalizeUser(userData);
    user.value = normalized;
    isAdmin.value = normalized?.type === "admin";
  };

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

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

  return {
    user,
    isAdmin,
    setUser,
    resetUser,
    fetchUser,
    accessToken,
  };
});
