import type { LayoutStorage } from './layout-storage';
import type { WorkbenchLayout } from './workbench-layout-types';

const KEY_PREFIX = 'rdms-workbench-layout';

function buildKey(userId: string) {
  return `${KEY_PREFIX}-${userId}`;
}

export class LocalStorageAdapter implements LayoutStorage {
  // 版本校验交给上层（use-workbench-layout.load）：版本不匹配时上层需要拿到旧 settings 做迁移，
  // 这里直接返回 raw 解析结果，只过滤掉无法解析的脏数据
  // eslint-disable-next-line class-methods-use-this
  async load(userId: string): Promise<WorkbenchLayout | null> {
    try {
      const raw = window.localStorage.getItem(buildKey(userId));
      if (!raw) return null;
      return JSON.parse(raw) as WorkbenchLayout;
    } catch {
      return null;
    }
  }

  // eslint-disable-next-line class-methods-use-this
  async save(userId: string, layout: WorkbenchLayout): Promise<void> {
    window.localStorage.setItem(buildKey(userId), JSON.stringify(layout));
  }
}
