export type CacheEventType =
  | 'list_updated'
  | 'detail_updated'
  | 'cache_state_updated'
  | 'error';

export interface CacheEvent<TPayload = any> {
  type: CacheEventType;
  payload: TPayload;
  timestamp: number;
}

export type CacheSubscriber<TEvent extends CacheEvent = CacheEvent> = (event: TEvent) => void;

/**
 * 统一缓存总线基座：
 * - 单一订阅入口
 * - 统一事件通知
 * - 新订阅立即收到快照
 */
export abstract class CacheBus<TSnapshot, TEvent extends CacheEvent = CacheEvent> {
  private subscribers = new Set<CacheSubscriber<TEvent>>();

  protected abstract getSnapshot(): TSnapshot;

  protected notify(event: TEvent): void {
    this.subscribers.forEach((subscriber) => {
      try {
        subscriber(event);
      } catch (error) {
        console.error('[CacheBus] subscriber error:', error);
      }
    });
  }

  subscribe(subscriber: CacheSubscriber<TEvent>): () => void {
    this.subscribers.add(subscriber);
    this.emitInitialSnapshot(subscriber);
    return () => {
      this.subscribers.delete(subscriber);
    };
  }

  protected emitInitialSnapshot(subscriber: CacheSubscriber<TEvent>): void {
    subscriber({
      type: 'cache_state_updated',
      payload: this.getSnapshot(),
      timestamp: Date.now(),
    } as TEvent);
  }
}

