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

const STORAGE_KEY = "gc_selected_unit_id";

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

  /** Lista de unidades do usuário atual */
  const userUnits = computed(() => user.value?.units ?? []);

  /** Inicializa a unidade ativa: tenta restaurar a última escolha salva ou usa a primeira */
  const initSelectedUnit = (units) => {
    if (!units?.length) return;
    const savedId = parseInt(localStorage.getItem(STORAGE_KEY));
    const saved = savedId ? units.find((u) => u.id === savedId) : null;
    selectedUnit.value = saved || units[0];
  };

  const setUser = (userData) => {
    user.value = userData;
    isAdmin.value = ["ADMIN", "ADMIN_FRANCHISEE"].includes(
      userData.user_type_system_key,
    );
    initSelectedUnit(userData.units);
  };

  /** Troca a unidade ativa e persiste a escolha */
  const setSelectedUnit = (unit) => {
    selectedUnit.value = unit;
    if (unit?.id) {
      localStorage.setItem(STORAGE_KEY, unit.id);
    } else {
      localStorage.removeItem(STORAGE_KEY);
    }
  };

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

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

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