import { reactive } from 'vue/dist/vue.esm-bundler.js';
import { getCurrentUser, login, logout } from './auth-api-client.js';
/** 代码作用（白话）：保存内存中的安全用户资料，页面刷新后只从后端 Cookie 恢复而不写入浏览器存储。关联文件：router/index.js、App.js。关联逻辑（调用链/数据流）：Auth API -> authState -> 路由守卫/菜单。 */
export const authState = reactive({ ready: false, user: null });
/** Plain purpose: remove a browser identity whose server-side session is no longer valid and return to the public login route. Related files: auth-api-client.js, router/index.js. Flow: protected API 401 -> browser event -> authState clear -> login route. */
export function expireSession() { authState.user = null; authState.ready = true; if (typeof window !== 'undefined') window.location.hash = '#/login'; }
/** Plain purpose: receive a shared API-session-expired event without making auth-api-client and auth-store import each other. Related files: auth-api-client.js, auth-store.js. Flow: request helper -> browser event -> expireSession -> login route. */
if (typeof window !== 'undefined') window.addEventListener('xyw-auth-expired', expireSession);
/** 代码作用（白话）：向后端恢复一次当前会话，失败时清除内存身份。关联文件：auth-api-client.js。关联逻辑（调用链/数据流）：路由守卫 -> /api/auth/me -> authState。 */
export async function bootstrapAuth() { try { authState.user = await getCurrentUser(); } catch (_) { authState.user = null; } finally { authState.ready = true; } return authState.user; }
/** 代码作用（白话）：完成登录并保存安全用户资料供当前页面使用。关联文件：LoginView.js。关联逻辑（调用链/数据流）：表单 -> login API -> authState -> 跳转。 */
export async function signIn(credentials) { authState.user = await login(credentials); authState.ready = true; return authState.user; }
/** 代码作用（白话）：尝试登出并无论结果都清空本地身份。关联文件：App.js。关联逻辑（调用链/数据流）：登出 -> API -> authState 清空 -> 登录路由。 */
export async function signOut() { try { await logout(); } finally { authState.user = null; authState.ready = true; } }
