import { fetchAdminMeDeduped } from "@/lib/admin-fetch-me";
import { isAdminAuthRejected } from "@/lib/admin-auth-reject";
import { getAdminSessionState } from "@/stores/admin-session";
import { readToken } from "@/stores/admin-token";

/**
 * 用 `/auth/me` 校验本地 Token 是否仍有效；失败时清会话（不跳转，由调用方决定）。
 */
export async function verifyStoredAdminSession(): Promise<boolean> {
  const token = readToken();
  if (!token) {
    return false;
  }

  const session = getAdminSessionState();
  session.setBearerToken(token);

  try {
    const result = await fetchAdminMeDeduped();
    session.setAdminProfile(result.admin);
    return true;
  } catch (err) {
    if (isAdminAuthRejected(err)) {
      session.clearSession();
    }
    return false;
  }
}
