import { defineStore } from 'pinia' import type { User, LoginRequest, RegisterRequest, AuthResponse } from '~/types' interface AuthState { user: User | null token: string | null loading: boolean } export const useAuthStore = defineStore('auth', { state: (): AuthState => ({ user: null, token: null, loading: false, }), getters: { isAuthenticated: (state) => !!state.token, }, actions: { async login(email: string, password: string) { this.loading = true try { const api = useApi() const response = await api.post('/auth/login', { email, password }) this.token = response.token this.user = response.user await this.fetchUser() } finally { this.loading = false } }, async register(data: RegisterRequest) { this.loading = true try { const api = useApi() const response = await api.post('/auth/register', data) this.token = response.token this.user = response.user } finally { this.loading = false } }, async fetchUser() { if (!this.token) return try { const api = useApi() const profile = await api.get>('/me') this.user = this.user ? { ...this.user, ...profile } : (profile as User) } catch { this.token = null this.user = null } }, async refreshToken(): Promise { try { const api = useApi() const response = await api.post<{ token: string }>('/auth/refresh') this.token = response.token return true } catch { this.token = null this.user = null return false } }, logout() { this.token = null this.user = null }, }, })