import { computed } from 'vue' import { useAuthStore } from '@/stores/authStore' interface MeResponse { name: string documento: string email: string roles: string[] } const FETCH_HEADERS = { 'X-Requested-With': 'fetch' } export function useAuth() { const store = useAuthStore() const router = useRouter() async function login(documento?: string, returnTo?: string) { const res = await $fetch<{ authUrl: string }>('/api/auth/login', { method: 'POST', headers: FETCH_HEADERS, body: { documento, returnTo }, }) if (import.meta.client) { window.location.href = res.authUrl } } async function fetchMe(): Promise { try { const me = await $fetch('/api/auth/me') store.setUser(me) return me } catch { store.clearUser() return null } } async function logout() { try { const res = await $fetch<{ logoutUrl: string }>('/api/auth/logout', { method: 'POST', headers: FETCH_HEADERS, }) store.clearUser() if (import.meta.client) { window.location.href = res.logoutUrl } } catch { store.clearUser() await router.push('/') } } return { user: computed(() => store.user), isAuthenticated: computed(() => store.isAuthenticated), nomeUsuario: computed(() => store.nomeUsuario), documento: computed(() => store.documento), roles: computed(() => store.roles), login, logout, fetchMe, } }