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

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

  constructor(
    @Inject("EMAIL_SERVICE")
    private readonly emailServiceClient: ClientProxy,
  ) {}

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

  async onApplicationBootstrap() {
    if (!this.enabled) return;
    this.emailServiceClient
      .connect()
      .then(() => this.logger.log("Connected to Email service"))
      .catch((err) =>
        this.logger.error("Error connecting to Email service", err),
      );
  }

  async sendEmail(dto: SendEmail): Promise<{ queued: boolean }> {
    if (!this.enabled) {
      this.logger.warn(`RABBITMQ disabled — skipped EMAIL`);
      return { queued: false };
    }
    this.emailServiceClient.emit("send-email", {
      ...dto,
      appKey: "IFHCRS-LICENSE-MANAGEMENT",
    });
    // Fire-and-forget enqueue: this confirms the message was handed to RabbitMQ, NOT delivered.
    this.logger.log(
      `EMAIL queued to RabbitMQ [${process.env.EMAIL_QUEUE ?? "email_queue"}] pattern='send-email'`,
    );
    // Recipient + content are PII — keep them at debug level only.
    this.logger.debug(
      `EMAIL payload to=${dto.to} subject="${dto.subject ?? ""}" body="${dto.text ?? dto.body ?? dto.html ?? ""}"`,
    );
    return { queued: true };
  }
}
