import { ref } from 'vue' import { defineStore } from 'pinia' import { useAppStore } from './app' import { useNotificationStore } from './notification' import { UserRole } from '@/generated/RpcClient' interface LoginFormData { login: string password: string rememberMe: boolean } export const useAuthStore = defineStore('auth', () => { const appStore = useAppStore() const loginForm = ref({ login: '', password: '', rememberMe: false }) const showLoginForm = ref(false) const notificationStore = useNotificationStore() const showSuccess = notificationStore.showSuccess const showError = notificationStore.showError const initializeAuth = async () => { if (!appStore.api) return appStore.setLoading(true) try { const user = await appStore.api.Profile.get() appStore.setCurrentUser(user) if (user.role === UserRole.Guest) { const authToken = localStorage.getItem('auth-token') if (authToken) { const success = await appStore.api.Auth.authenticateByToken(authToken) if (success) { const updatedUser = await appStore.api.Profile.get() appStore.setCurrentUser(updatedUser) } else { localStorage.removeItem('auth-token') showLoginForm.value = true } } else { showLoginForm.value = true } } } catch (error) { console.error('Auth initialization error:', error) showLoginForm.value = true } finally { appStore.setLoading(false) } } const login = async () => { if (!appStore.api) return false appStore.setLoading(true) try { const success = await appStore.api.Auth.authenticateByPassword( loginForm.value.login, loginForm.value.password ) if (success) { const user = await appStore.api.Profile.get() appStore.setCurrentUser(user) if (loginForm.value.rememberMe) { const tokenData = await appStore.api.Auth.generateToken(true) localStorage.setItem('auth-token', tokenData.uuid) } showSuccess('Авторизация успешна!') resetLoginForm() showLoginForm.value = false return true } else { showError('Неверный логин или пароль') return false } } catch (error) { console.error('Login error:', error) showError('Ошибка авторизации') return false } finally { appStore.setLoading(false) } } const logout = async () => { if (!appStore.api) return try { await appStore.api.Auth.logout() localStorage.removeItem('auth-token') appStore.setCurrentUser({ ...appStore.currentUser!, role: UserRole.Guest }) showLoginForm.value = true } catch (error) { console.error('Logout error:', error) } } const resetLoginForm = () => { loginForm.value = { login: '', password: '', rememberMe: false } } return { loginForm, showLoginForm, initializeAuth, login, logout, resetLoginForm } })