/**
 * 认证工具：token 存储 + 路由保护
 *
 * 仲裁：ARB-002 复用 Shell /login，admin-portal 不自行实现登录页
 * 开发期：standalone 壳提供 mock 登录（MSW 拦截 /api/auth/login）
 */

const TOKEN_KEY = "edu_access_token";
const USER_KEY = "edu_user_info";

import type { CurrentUser } from "@/types/view-models";

export function getToken(): string | null {
  if (typeof window === "undefined") return null;
  return localStorage.getItem(TOKEN_KEY);
}

export function setToken(token: string): void {
  if (typeof window === "undefined") return;
  localStorage.setItem(TOKEN_KEY, token);
}

export function clearToken(): void {
  if (typeof window === "undefined") return;
  localStorage.removeItem(TOKEN_KEY);
  localStorage.removeItem(USER_KEY);
}

export function getUser(): CurrentUser | null {
  if (typeof window === "undefined") return null;
  const raw = localStorage.getItem(USER_KEY);
  if (!raw) return null;
  try {
    return JSON.parse(raw) as CurrentUser;
  } catch {
    return null;
  }
}

export function setUser(user: CurrentUser): void {
  if (typeof window === "undefined") return;
  localStorage.setItem(USER_KEY, JSON.stringify(user));
}

export function isAuthenticated(): boolean {
  return getToken() !== null;
}

/** 调用登录 API（MSW 拦截 / api-gateway 代理到 iam） */
export async function login(
  email: string,
  password: string,
): Promise<{ user: CurrentUser; token: string }> {
  const res = await fetch("/api/auth/login", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ email, password }),
  });
  const json = (await res.json()) as {
    success: boolean;
    data?: { user: CurrentUser; tokens: { accessToken: string } };
    error?: { message: string };
  };
  if (!json.success || !json.data) {
    throw new Error(json.error?.message || "登录失败");
  }
  const user = json.data.user;
  const token = json.data.tokens.accessToken;
  setToken(token);
  setUser(user);
  return { user, token };
}

export function logout(): void {
  clearToken();
  if (typeof window !== "undefined") {
    window.location.href = "/login";
  }
}
