import { Injectable, Logger } from '@nestjs/common';
import { OnEvent } from '@nestjs/event-emitter';
import { SmsSentEvent } from '../events/sms.events';
import { RestRepository } from '../../restaurants/repositories/rest.repository';
import { EntityManager } from '@mikro-orm/postgresql';
import { SmsLog } from '../entities/smsLogs.entity';

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

  constructor(
    private readonly restRepository: RestRepository,
    private readonly em: EntityManager,
  ) {
  }

  @OnEvent(SmsSentEvent.name)
  async handleSmsSent(event: SmsSentEvent) {
    try {
      this.logger.log(
        `SMS sent event received: phone ${event.phoneNumber} for restaurant: ${event.restaurantId}`,
      );

      // Get the restaurant entity
      const restaurant = await this.restRepository.findOne({ id: event.restaurantId });

      if (!restaurant) {
        this.logger.warn(
          `Restaurant not found for SMS log: ${event.restaurantId}`,
        );
        return;
      }

      // Create SMS log record
      const smsLog = this.em.create(SmsLog, {
        restaurant: restaurant,
        phone: event.phoneNumber,
        createdAt: new Date(),
      });

      await this.em.flush();

      this.logger.log(
        `SMS log created successfully: ${smsLog.id} for phone ${event.phoneNumber}`,
      );
    } catch (error) {
      this.logger.error(
        `Failed to create SMS log for event: ${event.restaurantId}`,
        error instanceof Error ? error.stack : String(error),
      );
    }
  }

}