import { apiRequest, setAccessToken } from '@/shared/api/client' import type { AuthResponse, RegistrationStatus } from '@/shared/api/types' import { useAuthStore } from './store' /** Публично: включена ли открытая регистрация (для страниц входа/регистрации). */ export function fetchRegistrationStatus() { return apiRequest('/auth/registration') } export function login(userName: string, password: string) { return apiRequest('/auth/login', { method: 'POST', body: { userName, password } }) } export function register(userName: string, password: string) { return apiRequest('/auth/register', { method: 'POST', body: { userName, password } }) } export function logout() { return apiRequest('/auth/logout', { method: 'POST' }) } export function changePassword(currentPassword: string, newPassword: string) { return apiRequest('/auth/change-password', { method: 'POST', body: { currentPassword, newPassword } }) } export function changeUserName(newUserName: string) { return apiRequest('/auth/change-username', { method: 'POST', body: { newUserName } }) } export function deleteAccount() { return apiRequest('/auth/me', { method: 'DELETE' }) } export function applyAuthResponse(auth: AuthResponse) { setAccessToken(auth.accessToken) useAuthStore.getState().setUser(auth.user) } /** Тихая попытка восстановить сессию по refresh-cookie при загрузке приложения. */ export async function bootstrapSession() { try { const auth = await apiRequest('/auth/refresh', { method: 'POST', skipRefresh: true }) applyAuthResponse(auth) } catch { setAccessToken(null) useAuthStore.getState().setUser(null) } finally { useAuthStore.getState().finishBootstrap() } } export function clearSession() { setAccessToken(null) useAuthStore.getState().setUser(null) }