/**
 * 全局凭证管理器单例
 *
 * 为其他模块提供统一的凭证管理器实例
 */

import { CredentialManagerFactory } from './CredentialManagerFactory';
import { ICredentialManager } from './CredentialManager';
import { CredentialManagerOptions } from './types';

export class GlobalCredentialManager {
  private static instance: ICredentialManager | null = null;
  private static isInitialized = false;

  /**
   * 获取全局凭证管理器实例
   */
  public static async getInstance(options?: CredentialManagerOptions): Promise<ICredentialManager> {
    if (!this.instance || !this.isInitialized) {
      const factory = new CredentialManagerFactory();
      this.instance = await factory.create(options);
      this.isInitialized = true;
    }
    return this.instance;
  }

  /**
   * 重置全局实例
   */
  public static async reset(): Promise<void> {
    if (this.instance) {
      await this.instance.destroy();
      this.instance = null;
      this.isInitialized = false;
    }
  }

  /**
   * 检查是否已初始化
   */
  public static isReady(): boolean {
    return this.isInitialized && this.instance !== null;
  }
}

// 便捷的导出函数
export async function getGlobalCredentialManager(options?: CredentialManagerOptions): Promise<ICredentialManager> {
  return GlobalCredentialManager.getInstance(options);
}