import { Provide, Scope, ScopeEnum } from '@midwayjs/core';
import type { AppAdapter } from './adapter.js';

@Provide()
@Scope(ScopeEnum.Singleton)
export class AdapterRegistry {
  private map = new Map<string, AppAdapter>();

  /** 注册一个应用适配器(同 appId 重复注册抛错) */
  register(adapter: AppAdapter): void {
    if (!adapter.appId) throw new Error('adapter-missing-appId');
    if (this.map.has(adapter.appId)) {
      throw new Error('adapter-already-registered: ' + adapter.appId);
    }
    this.map.set(adapter.appId, adapter);
  }

  /** 按 appId 取适配器,找不到抛 'app-not-allowed' */
  get(appId: string): AppAdapter {
    const a = this.map.get(appId);
    if (!a) throw new Error('app-not-allowed: ' + appId);
    return a;
  }

  /** 列出所有已注册 appId */
  listAppIds(): string[] {
    return [...this.map.keys()];
  }

  /** 测试用:清空注册表 */
  clear(): void {
    this.map.clear();
  }
}
