import { computed, ref } from "vue";

import { api, ensureCsrf, resetCsrfState } from "../services/api";

const userRef = ref(null);

const initialized = ref(false);

export async function hydrateUser() {
  await ensureCsrf();
  try {
    const { data } = await api.get("/api/user");
    userRef.value = data;
  } catch {
    userRef.value = null;
  }
  initialized.value = true;
}

export function useAuth() {
  const user = computed(() => userRef.value);
  const permissions = computed(() => user.value?.permissions ?? []);
  const roles = computed(() => user.value?.roles ?? []);

  async function logout() {
    try {
      await ensureCsrf();
      await api.post("/logout");
    } catch {
      // session may already be expired
    } finally {
      userRef.value = null;
      resetCsrfState();
      initialized.value = true;
    }
  }

  return {
    user,
    permissions,
    roles,
    logout,
    initialized,
    isAuthenticated: computed(() => Boolean(user.value)),
  };
}

export function setUser(next) {
  userRef.value = next;
}

export { userRef };
