const TOKEN_KEY = 'sofio_access_token';
const REFRESH_TOKEN_KEY = 'sofio_refresh_token';
const TOKEN_EXPIRY_KEY = 'sofio_token_expiry';
const REFRESH_TOKEN_EXPIRY_KEY = 'sofio_refresh_token_expiry';
const USER_INFO_KEY = 'sofio_user_info';

// 保存 Token
export function saveTokens(tokens: AuthAPI.Tokens): void {
  localStorage.setItem(TOKEN_KEY, tokens.accessToken);
  localStorage.setItem(REFRESH_TOKEN_KEY, tokens.refreshToken);
  localStorage.setItem(TOKEN_EXPIRY_KEY, tokens.accessTokenExpiry);
  localStorage.setItem(REFRESH_TOKEN_EXPIRY_KEY, tokens.refreshTokenExpiry);
}

// 获取 Access Token
export function getAccessToken(): string | null {
  return localStorage.getItem(TOKEN_KEY);
}

// 获取 Refresh Token
export function getRefreshToken(): string | null {
  return localStorage.getItem(REFRESH_TOKEN_KEY);
}

// 获取 Token 过期时间
export function getTokenExpiry(): Date | null {
  const expiry = localStorage.getItem(TOKEN_EXPIRY_KEY);
  return expiry ? new Date(expiry) : null;
}

// 检查 Access Token 是否过期（提前 1 分钟判定为过期）
export function isTokenExpired(): boolean {
  const expiry = getTokenExpiry();
  if (!expiry) return true;
  return new Date().getTime() > expiry.getTime() - 60 * 1000;
}

// 检查 Refresh Token 是否过期
export function isRefreshTokenExpired(): boolean {
  const expiry = localStorage.getItem(REFRESH_TOKEN_EXPIRY_KEY);
  if (!expiry) return true;
  return new Date().getTime() > new Date(expiry).getTime();
}

// 清除所有 Token
export function clearTokens(): void {
  localStorage.removeItem(TOKEN_KEY);
  localStorage.removeItem(REFRESH_TOKEN_KEY);
  localStorage.removeItem(TOKEN_EXPIRY_KEY);
  localStorage.removeItem(REFRESH_TOKEN_EXPIRY_KEY);
  localStorage.removeItem(USER_INFO_KEY);
}

// 保存用户信息
export function saveUserInfo(user: AuthAPI.UserInfo): void {
  localStorage.setItem(USER_INFO_KEY, JSON.stringify(user));
}

// 获取用户信息
export function getUserInfo(): AuthAPI.UserInfo | null {
  const user = localStorage.getItem(USER_INFO_KEY);
  return user ? JSON.parse(user) : null;
}

// 更新 Access Token（刷新后）
export function updateAccessToken(accessToken: string, accessTokenExpiry: string): void {
  localStorage.setItem(TOKEN_KEY, accessToken);
  localStorage.setItem(TOKEN_EXPIRY_KEY, accessTokenExpiry);
}

// 检查是否已登录
export function isLoggedIn(): boolean {
  const token = getAccessToken();
  const refreshToken = getRefreshToken();
  return !!(token && refreshToken && !isRefreshTokenExpired());
}
