// ============================================================
// infrastructure/storage/user-scope.ts — 用户作用域工具
//
// 职责：
//   - 从 JWT refresh_token 提取当前用户 ID
//   - 生成日期键（YYYY-MM-DD）用于按日期分区
//   - URL 哈希（djb2）用于去重查询
// ============================================================

import { getSafeStore } from '@/shared/utils/safe-storage';

const REFRESH_KEY = 'ele-heixiu-refresh-token';

// ---------- 用户 ID ----------

let cachedUserId: string | null = null;
let cacheTs = 0;
const CACHE_MS = 30_000;

function extractIdFromJWT(token: string): string | null {
  try {
    const p = JSON.parse(atob(token.split('.')[1]));
    return (p.user_id as string) || (p.sub as string) || null;
  } catch {
    return null;
  }
}

/** 获取当前用户 ID（JWT 解码 + 30s 缓存），未登录返回 'anonymous' */
export function getCurrentUserId(): string {
  const now = Date.now();
  if (cachedUserId !== null && now - cacheTs < CACHE_MS) return cachedUserId;

  const token = getSafeStore(REFRESH_KEY);
  if (token) {
    const id = extractIdFromJWT(token);
    if (id) { cachedUserId = id; cacheTs = now; return id; }
  }

  cachedUserId = 'anonymous';
  cacheTs = now;
  return 'anonymous';
}

export function clearUserIdCache(): void {
  cachedUserId = null;
  cacheTs = 0;
}

// ---------- 日期键 ----------

export function getTodayKey(): string {
  const d = new Date();
  return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
}

export function dateKeyFromTs(ts: number): string {
  const d = new Date(ts);
  return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
}

// ---------- URL 哈希 ----------

export function hashURL(url: string): string {
  let h = 5381;
  for (let i = 0; i < url.length; i++) {
    h = ((h << 5) + h) ^ url.charCodeAt(i);
    h = h >>> 0;
  }
  return h.toString(16).padStart(8, '0');
}

// ---------- 格式化 ----------

export function formatBytes(bytes: number): string {
  if (bytes < 1024) return `${bytes} B`;
  if (bytes < 1048576) return `${(bytes / 1024).toFixed(1)} KB`;
  if (bytes < 1073741824) return `${(bytes / 1048576).toFixed(1)} MB`;
  return `${(bytes / 1073741824).toFixed(2)} GB`;
}
