import { logger } from '../../utils/logger';

/**
 * Domain Event
 * @description 领域事件接口
 */
export interface DomainEvent {
  tenantId: string;
  traceId?: string;
  userId?: string;
  module: string;
  action: string;
  resourceType: string;
  resourceId?: string;
  data: any;
  timestamp: number;
}

/**
 * Domain Event Bus
 * @description 领域事件总线，负责处理领域事件
 */
export class DomainEventBus {
  private static instance: DomainEventBus;
  private initialized: boolean = false;
  private handlers: Map<string, ((data: any) => void)[]> = new Map();

  private constructor() {
    // 私有构造函数
  }

  /**
   * 获取实例
   */
  static getInstance(): DomainEventBus {
    if (!DomainEventBus.instance) {
      DomainEventBus.instance = new DomainEventBus();
      logger.info('🚀 DomainEventBus initialized');
    }
    return DomainEventBus.instance;
  }

  /**
   * 静态发布事件
   */
  static publish(event: string, data: any): void {
    DomainEventBus.getInstance().publish(event, data);
  }

  /**
   * 静态发射事件
   */
  static emit(event: string, data: any): void {
    DomainEventBus.getInstance().emit(event, data);
  }

  /**
   * 初始化事件总线
   */
  async initialize(): Promise<void> {
    if (this.initialized) {
      return;
    }
    logger.info('[DomainEventBus] Initializing...');
    this.initialized = true;
    logger.info('[DomainEventBus] Initialized successfully');
  }

  /**
   * 发布事件
   */
  publish(event: string, data: any): void {
    logger.info(`[DomainEventBus] Published event: ${event}`);
    const handlers = this.handlers.get(event) || [];
    handlers.forEach(handler => {
      try {
        handler(data);
      } catch (error) {
        logger.error(`[DomainEventBus] Handler error for event ${event}: ${error}`);
      }
    });
  }

  /**
   * 发射事件（publish别名）
   */
  emit(event: string, data: any): void {
    this.publish(event, data);
  }

  /**
   * 订阅事件
   */
  subscribe(event: string, handler: (data: any) => void): void {
    logger.info(`[DomainEventBus] Subscribed to event: ${event}`);
    const handlers = this.handlers.get(event) || [];
    handlers.push(handler);
    this.handlers.set(event, handlers);
  }

  /**
   * 订阅所有事件
   */
  subscribeAll(handler: (event: DomainEvent) => void): void {
    logger.info('[DomainEventBus] Subscribed to all events');
    // 这里可以添加订阅所有事件的逻辑
  }

  /**
   * 关闭事件总线
   */
  async shutdown(): Promise<void> {
    logger.info('[DomainEventBus] Shutting down...');
    this.handlers.clear();
    this.initialized = false;
    logger.info('[DomainEventBus] Shutdown complete');
  }
}
