/**
 * 基于文件的凭据仓储实现
 * 负责从JSON配置文件加载和管理凭据数据
 */

import { EventEmitter } from 'events'
import { ICredentialRepository } from '../interfaces/ICredentialRepository'
import { CredentialConfigLoader } from '../../core/config-loader'
import { PlatformAccount } from '../../shared/credential-types'

export class FileCredentialRepository extends EventEmitter implements ICredentialRepository {
  private _configLoader: CredentialConfigLoader
  private _watching = false

  constructor(configPath?: string) {
    super()
    this._configLoader = new CredentialConfigLoader(configPath)

    // 转发事件
    this._configLoader.on('config:loaded', event => this.emit('config:loaded', event))
    this._configLoader.on('config:reloaded', event => this.emit('config:reloaded', event))
    this._configLoader.on('config:error', event => this.emit('config:error', event))
  }

  async load(): Promise<void> {
    await this._configLoader.loadConfig()
  }

  async reload(): Promise<void> {
    await this._configLoader.reloadConfig()
  }

  findAccount(platformId: string, accountId: string): PlatformAccount | null {
    return this._configLoader.getAccount(platformId, accountId)
  }

  findAccountsByPlatform(platformId: string): PlatformAccount[] {
    return this._configLoader.getAccountsByPlatform(platformId)
  }

  getAllAccounts(): PlatformAccount[] {
    return Array.from(this._configLoader.accounts.values())
  }

  hasAccount(platformId: string, accountId: string): boolean {
    return this.findAccount(platformId, accountId) !== null
  }

  getStats() {
    const stats = this._configLoader.getStats()
    return {
      totalAccounts: stats.totalAccounts,
      platformStats: stats.platformStats,
      lastLoaded: stats.lastLoaded,
      configPath: stats.configPath,
    }
  }

  startWatching(): void {
    if (!this._watching) {
      this._configLoader.watchConfig()
      this._watching = true
    }
  }

  stopWatching(): void {
    this._watching = false
    // 注意：CredentialConfigLoader没有停止监控的方法，这里只是标记状态
  }

  async dispose(): Promise<void> {
    this.stopWatching()
    await this._configLoader.shutdown()
    this.removeAllListeners()
  }
}
