import { reactive, computed } from 'vue' import { authApi } from '@/api' import { setToken, getToken, tryRefresh } from '@/api/client' import type { LoginResult, User } from '@/types' const state = reactive<{ user: User | null ready: boolean loading: boolean }>({ user: null, ready: false, loading: false, }) async function restore(): Promise { if (state.user) return if (!getToken()) { // No access token in storage: try the refresh cookie to recover a session. const fresh = await tryRefresh() if (!fresh) { state.ready = true return } setToken(fresh) } try { state.user = await authApi.me() } catch { state.user = null } finally { state.ready = true } } async function apply(result: LoginResult): Promise { setToken(result.token.accessToken) state.user = result.user } async function login(account: string, password: string): Promise { state.loading = true try { await apply(await authApi.login(account, password)) } finally { state.loading = false } } async function register(data: { username: string; email: string; password: string; inviteCode?: string }): Promise { state.loading = true try { await apply(await authApi.register(data)) } finally { state.loading = false } } async function logout(): Promise { try { await authApi.logout() } catch { // ignore network errors on logout } setToken('') state.user = null } async function refreshProfile(): Promise { if (!getToken()) return state.user = await authApi.me() } export function useAuth() { return { state, user: computed(() => state.user), isAdmin: computed(() => state.user?.role === 'admin'), isAuthed: computed(() => !!state.user), restore, login, register, logout, refreshProfile, } }