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, connectionError: false });
/** 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.connectionError = false; 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、router/index.js、App.js。关联逻辑（调用链/数据流）：路由守卫 -> /api/auth/me -> 401 交给路由跳登录，网络错误写入 connectionError -> App 显示重试页。 */
export async function bootstrapAuth() { const timeoutMs = typeof window !== 'undefined' && window.__XYW_AUTH_CHECK_TIMEOUT_MS ? window.__XYW_AUTH_CHECK_TIMEOUT_MS : 8000; let timeoutId; authState.connectionError = false; try { authState.user = await Promise.race([getCurrentUser(), new Promise((_, reject) => { timeoutId = window.setTimeout(() => reject(new Error('SESSION_CHECK_TIMEOUT')), timeoutMs); })]); } catch (error) { authState.user = null; authState.connectionError = error.status !== 401; } finally { if (timeoutId) window.clearTimeout(timeoutId); authState.ready = true; } return authState.user; }
/** 代码作用（白话）：完成登录并保存安全用户资料供当前页面使用。关联文件：LoginView.js。关联逻辑（调用链/数据流）：表单 -> login API -> authState -> 跳转。 */
export async function signIn(credentials) { authState.connectionError = false; 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.connectionError = false; authState.ready = true; } }
