/**
 * 浏览器工厂类
 * 使用泛型和类型安全
 */

import { IBrowserProvider } from '../core/interfaces/IBrowserProvider';
import { BrowserProviderType } from '../core/types';

type ProviderConstructor = new (config: any) => IBrowserProvider;

export class BrowserFactory {
  private static providers = new Map<string, ProviderConstructor>();

  /**
   * 注册Provider（TypeScript类型检查）
   */
  static register<T extends IBrowserProvider>(
    type: BrowserProviderType,
    ProviderClass: new (config: any) => T
  ): void {
    this.providers.set(type, ProviderClass);
    console.log(`✅ Provider "${type}" registered`);
  }

  /**
   * 创建Provider实例
   */
  static create<T extends IBrowserProvider = IBrowserProvider>(
    type: BrowserProviderType,
    config: any = {}
  ): T {
    const ProviderClass = this.providers.get(type);

    if (!ProviderClass) {
      const available = Array.from(this.providers.keys()).join(', ');
      throw new Error(
        `Unknown provider: "${type}"\nAvailable: ${available}`
      );
    }

    return new ProviderClass(config) as T;
  }

  /**
   * 获取所有已注册的Provider
   */
  static getAvailableProviders(): BrowserProviderType[] {
    return Array.from(this.providers.keys()) as BrowserProviderType[];
  }

  /**
   * 检查Provider是否已注册
   */
  static has(type: BrowserProviderType): boolean {
    return this.providers.has(type);
  }

  /**
   * 注销Provider
   */
  static unregister(type: BrowserProviderType): void {
    this.providers.delete(type);
  }
}
