/**
 * 凭据服务工厂
 * 实现依赖注入和控制反转，简化服务实例化
 */

import { CredentialService, CredentialServiceConfig } from './CredentialService'
import { FileCredentialRepository } from './repositories/FileCredentialRepository'
import { PacificaSignatureProvider } from './providers/PacificaSignatureProvider'
import { ICredentialRepository } from './interfaces/ICredentialRepository'
import { ISignatureProvider } from './interfaces/ISignatureProvider'
import { ICredentialService } from './interfaces/ICredentialService'

/**
 * 服务工厂配置
 */
export interface ServiceFactoryConfig {
  configPath?: string
  autoInitialize?: boolean
  enableWatching?: boolean
  performanceTracking?: boolean
  customRepository?: ICredentialRepository
  customProviders?: Map<string, ISignatureProvider>
}

/**
 * 凭据服务工厂类
 * 负责创建和配置完整的服务依赖图
 */
export class CredentialServiceFactory {
  private static _defaultInstance: CredentialServiceFactory

  /**
   * 获取默认工厂实例（单例）
   */
  static getDefault(): CredentialServiceFactory {
    if (!this._defaultInstance) {
      this._defaultInstance = new CredentialServiceFactory()
    }
    return this._defaultInstance
  }

  /**
   * 创建完整配置的凭据服务实例
   */
  createService(config: ServiceFactoryConfig = {}): ICredentialService {
    // 1. 创建仓储层
    const repository = config.customRepository || this.createRepository(config.configPath)

    // 2. 创建签名提供者
    const providers = config.customProviders || this.createDefaultProviders()

    // 3. 创建服务配置
    const serviceConfig: CredentialServiceConfig = {
      autoInitialize: config.autoInitialize ?? true,
      enableWatching: config.enableWatching ?? true,
      performanceTracking: config.performanceTracking ?? true,
    }

    // 4. 组装服务实例
    return new CredentialService(repository, providers, serviceConfig)
  }

  /**
   * 创建默认的文件仓储
   */
  createRepository(configPath?: string): ICredentialRepository {
    return new FileCredentialRepository(configPath)
  }

  /**
   * 创建默认的签名提供者集合
   */
  createDefaultProviders(): Map<string, ISignatureProvider> {
    const providers = new Map<string, ISignatureProvider>()

    // 添加 Pacifica 提供者
    const pacificaProvider = new PacificaSignatureProvider()
    providers.set(pacificaProvider.platformId, pacificaProvider)

    // 未来可以在这里添加其他平台提供者
    // providers.set('aster', new AsterSignatureProvider());
    // providers.set('binance', new BinanceSignatureProvider());

    return providers
  }

  /**
   * 创建自定义配置的服务实例
   */
  createCustomService(
    repository: ICredentialRepository,
    providers: Map<string, ISignatureProvider>,
    config?: CredentialServiceConfig,
  ): ICredentialService {
    return new CredentialService(repository, providers, config)
  }
}

/**
 * 流畅式服务构建器
 * 提供链式 API 来配置服务
 */
export class CredentialServiceBuilder {
  private _configPath?: string
  private _repository?: ICredentialRepository
  private _providers: Map<string, ISignatureProvider> = new Map()
  private _serviceConfig: CredentialServiceConfig = {}

  /**
   * 设置配置文件路径
   */
  withConfigPath(path: string): this {
    this._configPath = path
    return this
  }

  /**
   * 设置自定义仓储
   */
  withRepository(repository: ICredentialRepository): this {
    this._repository = repository
    return this
  }

  /**
   * 添加签名提供者
   */
  withProvider(provider: ISignatureProvider): this {
    this._providers.set(provider.platformId, provider)
    return this
  }

  /**
   * 启用/禁用自动初始化
   */
  autoInitialize(enabled: boolean = true): this {
    this._serviceConfig.autoInitialize = enabled
    return this
  }

  /**
   * 启用/禁用配置文件监控
   */
  enableWatching(enabled: boolean = true): this {
    this._serviceConfig.enableWatching = enabled
    return this
  }

  /**
   * 启用/禁用性能跟踪
   */
  enablePerformanceTracking(enabled: boolean = true): this {
    this._serviceConfig.performanceTracking = enabled
    return this
  }

  /**
   * 构建服务实例
   */
  build(): ICredentialService {
    const factory = CredentialServiceFactory.getDefault()

    // 使用自定义仓储或创建默认仓储
    const repository = this._repository || factory.createRepository(this._configPath)

    // 使用添加的提供者或创建默认提供者
    const providers = this._providers.size > 0 ? this._providers : factory.createDefaultProviders()

    return factory.createCustomService(repository, providers, this._serviceConfig)
  }
}

/**
 * 便捷函数：创建默认服务实例
 */
export function createCredentialService(config?: ServiceFactoryConfig): ICredentialService {
  return CredentialServiceFactory.getDefault().createService(config)
}

/**
 * 便捷函数：创建服务构建器
 */
export function credentialServiceBuilder(): CredentialServiceBuilder {
  return new CredentialServiceBuilder()
}
