import { Injectable, Logger } from '@nestjs/common';
import { EventPattern, Payload } from '@nestjs/microservices';
import { ContributionSyncService } from '../services/contribution-sync.service';

@Injectable()
export class ContributionEventHandler {
  private readonly logger = new Logger(ContributionEventHandler.name);

  constructor(private readonly syncService: ContributionSyncService) {}

  @EventPattern('contribution.ContributionCalculated')
  async handleContributionCalculated(@Payload() message: any): Promise<void> {
    try {
      const { payload } = message.value || message;
      this.logger.debug(`Received ContributionCalculated event for ${payload.accountSequence}`);

      await this.syncService.handleContributionCalculated({
        accountSequence: payload.accountSequence,
        personalContribution: payload.personalContribution,
        calculatedAt: payload.calculatedAt,
      });
    } catch (error) {
      this.logger.error('Failed to handle ContributionCalculated event', error);
    }
  }

  @EventPattern('contribution.DailySnapshotCreated')
  async handleDailySnapshotCreated(@Payload() message: any): Promise<void> {
    try {
      const { payload } = message.value || message;
      this.logger.log(`Received DailySnapshotCreated event for ${payload.snapshotDate}`);

      await this.syncService.handleDailySnapshotCreated({
        snapshotId: payload.snapshotId,
        snapshotDate: payload.snapshotDate,
        totalContribution: payload.totalContribution,
        activeAccounts: payload.activeAccounts,
      });
    } catch (error) {
      this.logger.error('Failed to handle DailySnapshotCreated event', error);
    }
  }
}
