import {
  Inject,
  Injectable,
  Logger,
  OnApplicationBootstrap,
} from "@nestjs/common";
import { ClientProxy } from "@nestjs/microservices";
import { BulkMessagesDto, SingleMessageDto } from "./dtos/sms.dto";

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

  constructor(
    @Inject("SMS_SERVICE")
    private smsClient: ClientProxy,
  ) {}

  private readonly enabled = process.env.RABBITMQ_ENABLED !== "false";

  async onApplicationBootstrap() {
    if (!this.enabled) return;
    this.smsClient
      .connect()
      .then(() => {
        this.logger.log("connected to SMS service");
      })
      .catch((err) => {
        console.error("Error happened at SMS service", err);
      });
  }

  async sendSms(dto: SingleMessageDto): Promise<{ queued: boolean }> {
    if (!this.enabled) {
      this.logger.warn(`RABBITMQ disabled — skipped SMS`);
      return { queued: false };
    }
    this.smsClient.emit("send-sms", {
      to: dto.to,
      text: dto.message,
      appKey: "IFHCRS-LICENSE-MANAGEMENT",
    });
    // Fire-and-forget enqueue: confirms hand-off to RabbitMQ, NOT delivery.
    this.logger.log(
      `SMS queued to RabbitMQ [${process.env.SMS_QUEUE ?? "sms_queue"}] pattern='send-sms'`,
    );
    // Recipient + content are PII — debug only.
    this.logger.debug(`SMS payload to=${dto.to} text="${dto.message}"`);
    return { queued: true };
  }

  async sendBulkMessages(dto: BulkMessagesDto): Promise<{ queued: boolean }> {
    if (!this.enabled) {
      this.logger.warn(`RABBITMQ disabled — skipped BULK SMS (${dto.messages?.length ?? 0} messages)`);
      return { queued: false };
    }
    const messages = (dto.messages ?? []).map((m) => ({ to: m.to, text: m.message, from: m.from }));
    this.smsClient.emit("ozeking-bulk-sms", {
      messages,
      appKey: "IFHCRS-LICENSE-MANAGEMENT",
    });
    this.logger.log(
      `BULK SMS queued to RabbitMQ [${process.env.SMS_QUEUE ?? "sms_queue"}] pattern='ozeking-bulk-sms' count=${messages.length}`,
    );
    this.logger.debug(`BULK SMS payload messages=${JSON.stringify(messages)}`);
    return { queued: true };
  }
}
