const EventEmitter = require('events');
const { logger } = require('./logger');

class AppEventEmitter extends EventEmitter {
  emit(event, data) {
    logger.debug({ event, hasListeners: this.listenerCount(event) > 0 }, 'Event emitted');
    return super.emit(event, data);
  }

  async emitAsync(event, data) {
    logger.debug({ event, listenerCount: this.listenerCount(event) }, 'Async event emitted');
    const results = await Promise.allSettled(
      this.listeners(event).map(listener => listener(data))
    );

    const failures = results.filter(r => r.status === 'rejected');
    if (failures.length > 0) {
      logger.warn({ event, failures: failures.map(f => f.reason?.message) }, 'Some event listeners failed');
    }

    return results;
  }

  onAsync(event, listener) {
    this.on(event, async (data) => {
      try {
        await listener(data);
      } catch (error) {
        logger.error({ event, error: error.message }, 'Async event listener error');
      }
    });
  }
}

const appEvents = new AppEventEmitter();

appEvents.on('user.created', (user) => {
  logger.info({ userId: user.id, email: user.email }, 'User created event received');
});

appEvents.on('project.created', (project) => {
  logger.info({ projectId: project.id, name: project.name }, 'Project created event received');
});

appEvents.on('project.published', (project) => {
  logger.info({ projectId: project.id, slug: project.slug }, 'Project published event received');
});

appEvents.on('error', (error) => {
  logger.error({ error: error.message }, 'Application event error');
});

module.exports = { appEvents, AppEventEmitter };
