import { logger as rootLogger } from '../config/logger'

// eslint-disable-next-line @typescript-eslint/no-explicit-any
type HookHandler = (data: any) => Promise<any>

/**
 * Event bus entre plugins.
 * emit() executa todos os handlers registrados e retorna array de resultados.
 * O plugin uploads usa o último resultado não-nulo retornado pelo SmartVision.
 */
export class HookBus {
  private handlers = new Map<string, HookHandler[]>()

  register(event: string, handler: HookHandler): void {
    if (!this.handlers.has(event)) {
      this.handlers.set(event, [])
    }
    this.handlers.get(event)!.push(handler)
    rootLogger.debug({ event }, '[HookBus] Handler registrado')
  }

  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  async emit(event: string, data: any): Promise<any[]> {
    const handlers = this.handlers.get(event)
    if (!handlers || handlers.length === 0) return []

    const results: unknown[] = []

    for (const handler of handlers) {
      try {
        const result = await handler(data)
        results.push(result)
      } catch (err) {
        rootLogger.error({ err, event }, '[HookBus] Erro em handler')
        results.push(null)
      }
    }

    return results
  }

  /** Remove todos os handlers de um evento (usado no deactivate de plugins) */
  removeAll(event: string): void {
    this.handlers.delete(event)
  }

  /** Lista eventos registrados — útil para debug */
  listEvents(): string[] {
    return Array.from(this.handlers.keys())
  }
}

export const hookBus = new HookBus()
