import {
  Inject,
  Injectable,
  Logger,
  OnApplicationBootstrap,
} from "@nestjs/common";
import { ClientProxy } from "@nestjs/microservices";
import * as sgMail from "@sendgrid/mail";
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,
  ) {
    const apiKey = process.env.SENDGRID_API_KEY;
    if (apiKey) sgMail.setApiKey(apiKey);
  }

  private readonly enabled = process.env.RABBITMQ_ENABLED !== "false";
  private get sendgridEnabled() {
    return !!process.env.SENDGRID_API_KEY;
  }

  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.emailServiceClient.emit("send-email", {
        ...dto,
        appKey: "IFHCRS-LICENSE-MANAGEMENT",
      });
      this.logger.log(
        `EMAIL queued to RabbitMQ [${process.env.EMAIL_QUEUE ?? "email_queue"}] pattern='send-email'`,
      );
      this.logger.debug(
        `EMAIL payload to=${dto.to} subject="${dto.subject ?? ""}"`,
      );
      return { queued: true };
    }

    if (this.sendgridEnabled) {
      try {
        await sgMail.send({
          to: dto.to,
          from: process.env.SENDGRID_FROM_EMAIL ?? "noreply@edr-platform.com",
          subject: dto.subject ?? "EDR Notification",
          text: dto.text ?? dto.body ?? "",
          ...(dto.html ? { html: dto.html } : {}),
        });
        this.logger.log(`EMAIL sent via SendGrid to=${dto.to}`);
        return { queued: true };
      } catch (err: any) {
        this.logger.error(`SendGrid send failed to=${dto.to}: ${err?.message}`);
        return { queued: false };
      }
    }

    this.logger.warn(`EMAIL not sent (no transport) — to=${dto.to} subject="${dto.subject ?? ""}"`);
    return { queued: false };
  }
}
