import Taro from "@tarojs/taro";

const TOKEN_KEY = "xlh_access_token";
const TOKEN_EXPIRY_KEY = "xlh_token_expiry";
const SMS_COOLDOWN_KEY = "xlh_sms_last_sent";
const SMS_COOLDOWN_MS = 60_000; // 60秒频控
const TOKEN_DEFAULT_TTL_MS = 24 * 60 * 60 * 1000; // 默认24小时

export function getToken() {
  return Taro.getStorageSync(TOKEN_KEY) || "";
}

export function setToken(token: string, ttlMs?: number) {
  Taro.setStorageSync(TOKEN_KEY, token);
  // 存储过期时间
  const expiry = Date.now() + (ttlMs || TOKEN_DEFAULT_TTL_MS);
  Taro.setStorageSync(TOKEN_EXPIRY_KEY, String(expiry));
}

/** 保存登录返回的完整凭证（accessToken + refreshToken） */
export function saveLoginTokens(data: { accessToken: string; refreshToken?: string }, ttlMs?: number) {
  setToken(data.accessToken, ttlMs);
  if (data.refreshToken) {
    setRefreshToken(data.refreshToken);
  }
}

export function clearToken() {
  Taro.removeStorageSync(TOKEN_KEY);
  Taro.removeStorageSync(TOKEN_EXPIRY_KEY);
  Taro.removeStorageSync(REFRESH_TOKEN_KEY);
}

/** 检查 token 是否即将过期（5分钟内）或已过期 */
export function isTokenExpiringSoon() {
  const expiry = Number(Taro.getStorageSync(TOKEN_EXPIRY_KEY) || 0);
  if (!expiry) return true; // 无过期时间记录，视为即将过期
  return Date.now() > expiry - 5 * 60 * 1000;
}

export function isTokenExpired() {
  const expiry = Number(Taro.getStorageSync(TOKEN_EXPIRY_KEY) || 0);
  if (!expiry) return false; // 无过期时间记录，由后端判断
  return Date.now() > expiry;
}

/** 记录短信发送时间（客户端频控） */
export function recordSmsSent() {
  Taro.setStorageSync(SMS_COOLDOWN_KEY, String(Date.now()));
}

/** 获取距离下次可发的剩余秒数 */
export function getSmsCooldownSeconds(): number {
  const lastSent = Number(Taro.getStorageSync(SMS_COOLDOWN_KEY) || 0);
  const elapsed = Date.now() - lastSent;
  if (elapsed >= SMS_COOLDOWN_MS) return 0;
  return Math.ceil((SMS_COOLDOWN_MS - elapsed) / 1000);
}

const REFRESH_TOKEN_KEY = "xlh_refresh_token";

export function getRefreshToken() {
  return Taro.getStorageSync(REFRESH_TOKEN_KEY) || "";
}

export function setRefreshToken(token: string) {
  Taro.setStorageSync(REFRESH_TOKEN_KEY, token);
}

export function clearRefreshToken() {
  Taro.removeStorageSync(REFRESH_TOKEN_KEY);
}
