import { defineStore } from 'pinia' import { computed, ref } from 'vue' import { api, ApiError } from '../api/client' import type { TokenResponse, User } from '../api/types' export const useAuthStore = defineStore('auth', () => { const accessToken = ref(null) const user = ref(null) const isAuthenticated = computed(() => user.value !== null) const isAdmin = computed(() => user.value?.role === 'admin') function setSession(data: TokenResponse) { accessToken.value = data.access_token user.value = data.user } function clear() { accessToken.value = null user.value = null } async function login(email: string, password: string) { const res = await fetch('/api/auth/login', { method: 'POST', headers: { 'Content-Type': 'application/json' }, credentials: 'same-origin', body: JSON.stringify({ email, password }), }) const body = await res.json().catch(() => ({})) if (!res.ok) throw new ApiError(res.status, body.error ?? 'unknown', body.message ?? '') setSession(body as TokenResponse) } async function logout() { try { await api.post('/api/auth/logout') } finally { clear() } } return { accessToken, user, isAuthenticated, isAdmin, setSession, clear, login, logout } })