import { Controller, Logger } from '@nestjs/common';
import { MessagePattern, Payload } from '@nestjs/microservices';
import { OutboxRepository } from '../persistence/repositories/outbox.repository';

/**
 * 事件确认控制器
 * 接收来自其他服务的事件消费确认
 */
@Controller()
export class EventAckController {
  private readonly logger = new Logger(EventAckController.name);

  constructor(private readonly outboxRepository: OutboxRepository) {}

  @MessagePattern('transfer.events.ack')
  async handleEventAck(
    @Payload() message: { eventId: string; eventType?: string; status: string },
  ): Promise<void> {
    this.logger.log(`[ACK] Received ack for event ${message.eventId} (${message.eventType || 'any'})`);

    if (message.status === 'SUCCESS') {
      await this.outboxRepository.markAsConfirmed(message.eventId, message.eventType);
    } else {
      this.logger.warn(`[ACK] Event ${message.eventId} reported failure: ${message.status}`);
    }
  }
}
