import { defineStore } from 'pinia' import { ref, computed } from 'vue' import api from '@/services/api' import type { AuthResponse } from '@/types' export const useAuthStore = defineStore('auth', () => { const token = ref(null) const refreshTokenValue = ref(null) const username = ref(null) const expiresAt = ref(null) const isAuthenticated = computed(() => !!token.value) function initialize() { token.value = localStorage.getItem('purrse_token') refreshTokenValue.value = localStorage.getItem('purrse_refresh_token') username.value = localStorage.getItem('purrse_username') expiresAt.value = localStorage.getItem('purrse_expires_at') } function setAuth(auth: AuthResponse) { token.value = auth.token refreshTokenValue.value = auth.refreshToken username.value = auth.username expiresAt.value = auth.expiresAt localStorage.setItem('purrse_token', auth.token) localStorage.setItem('purrse_refresh_token', auth.refreshToken) localStorage.setItem('purrse_username', auth.username) localStorage.setItem('purrse_expires_at', auth.expiresAt) } async function login(usernameInput: string, password: string) { const { data } = await api.post('/auth/login', { username: usernameInput, password }) setAuth(data) } async function register(usernameInput: string, email: string, password: string) { const { data } = await api.post('/auth/register', { username: usernameInput, email, password }) setAuth(data) } async function refreshToken() { if (!refreshTokenValue.value) throw new Error('No refresh token') const { data } = await api.post('/auth/refresh', { refreshToken: refreshTokenValue.value }) setAuth(data) } function logout() { token.value = null refreshTokenValue.value = null username.value = null expiresAt.value = null localStorage.removeItem('purrse_token') localStorage.removeItem('purrse_refresh_token') localStorage.removeItem('purrse_username') localStorage.removeItem('purrse_expires_at') } return { token, username, expiresAt, isAuthenticated, initialize, login, register, refreshToken, logout } })