// sessionStorage 操作封装

const PREFIX = 'rwadurian_admin_';

export const sessionStorageService = {
  get<T>(key: string): T | null {
    if (typeof window === 'undefined') return null;
    try {
      const item = sessionStorage.getItem(PREFIX + key);
      return item ? JSON.parse(item) : null;
    } catch {
      return null;
    }
  },

  set<T>(key: string, value: T): void {
    if (typeof window === 'undefined') return;
    try {
      sessionStorage.setItem(PREFIX + key, JSON.stringify(value));
    } catch (error) {
      console.error('sessionStorage set error:', error);
    }
  },

  remove(key: string): void {
    if (typeof window === 'undefined') return;
    sessionStorage.removeItem(PREFIX + key);
  },

  clear(): void {
    if (typeof window === 'undefined') return;
    Object.keys(sessionStorage)
      .filter((key) => key.startsWith(PREFIX))
      .forEach((key) => sessionStorage.removeItem(key));
  },
};

// 常用 key
export const SESSION_KEYS = {
  CURRENT_PAGE: 'current_page',
  FILTERS: 'filters',
  SCROLL_POSITION: 'scroll_position',
} as const;
