import { Injectable, Logger, OnModuleInit } from '@nestjs/common';
import { NotificationService } from './notification.service';
import { NotificationChannel } from '../../domain/entities/notification.entity';

/**
 * Kafka event consumer - listens for domain events and triggers notifications.
 * Simplified event consumer. Can be extended with @genex/kafka-client for full Kafka integration.
 */
@Injectable()
export class EventConsumerService implements OnModuleInit {
  private readonly logger = new Logger('EventConsumer');
  constructor(private readonly notificationService: NotificationService) {}

  async onModuleInit() {
    this.logger.log('Event consumer ready (will connect to Kafka when configured)');
  }

  async handleUserRegistered(event: { userId: string; phone?: string; email?: string }): Promise<void> {
    await this.notificationService.send({
      userId: event.userId,
      channel: NotificationChannel.IN_APP,
      title: 'Welcome to Genex!',
      body: 'Your account has been created successfully. Complete your KYC to unlock all features.',
      data: { type: 'welcome' },
    });
  }

  async handleTradeMatched(event: {
    buyerId: string;
    sellerId: string;
    couponId: string;
    price: number;
    quantity: number;
  }): Promise<void> {
    await this.notificationService.send({
      userId: event.buyerId,
      channel: NotificationChannel.IN_APP,
      title: 'Trade Executed',
      body: `Your buy order was filled: ${event.quantity} unit(s) at $${event.price}`,
      data: { type: 'trade', couponId: event.couponId },
    });
    await this.notificationService.send({
      userId: event.sellerId,
      channel: NotificationChannel.IN_APP,
      title: 'Trade Executed',
      body: `Your sell order was filled: ${event.quantity} unit(s) at $${event.price}`,
      data: { type: 'trade', couponId: event.couponId },
    });
  }

  async handleKycApproved(event: { userId: string; level: number }): Promise<void> {
    await this.notificationService.send({
      userId: event.userId,
      channel: NotificationChannel.IN_APP,
      title: 'KYC Approved',
      body: `Your KYC verification has been approved. You are now at Level ${event.level}.`,
      data: { type: 'kyc', level: event.level },
    });
  }

  async handleAmlAlert(event: { userId: string; pattern: string; riskScore: number }): Promise<void> {
    await this.notificationService.send({
      userId: event.userId,
      channel: NotificationChannel.IN_APP,
      title: 'Security Notice',
      body: 'We have detected unusual activity on your account. Please verify your recent transactions.',
      data: { type: 'security' },
    });
  }
}
