import { OnEvent } from '@nestjs/event-emitter';
import { Injectable } from '@nestjs/common';
import { NotificationService } from '../../core/services/notification.service';
import { NotificationRuleService } from '../../core/services/notification-rule.service';

@Injectable()
export class TodoSubscriber {
  constructor(
    private readonly notificationService: NotificationService,
    private readonly notificationRuleService: NotificationRuleService,
  ) {}

  @OnEvent('todo.created')
  async handleTodoCreated(payload: any) {
    const { todo } = payload;
    const rules = await this.notificationRuleService.getRulesForEvent(todo.tenantId, 'todo', 'todo.created');
    for (const rule of rules) {
      for (const channel of rule.channels) {
        await this.notificationService.send(
          channel,
          todo.metadata?.notifyTo || '',
          'Nueva tarea creada',
          `Se creó la tarea: ${todo.title}`,
        );
      }
    }
  }

  @OnEvent('todo.completed')
  async handleTodoCompleted(payload: any) {
    const { todo } = payload;
    const rules = await this.notificationRuleService.getRulesForEvent(todo.tenantId, 'todo', 'todo.completed');
    for (const rule of rules) {
      for (const channel of rule.channels) {
        await this.notificationService.send(
          channel,
          todo.metadata?.notifyTo || '',
          'Tarea completada',
          `La tarea "${todo.title}" se ha marcado como completada.`,
        );
      }
    }
  }
}
