import { Injectable, Logger, OnModuleInit } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { RedisService } from '@chatapp/redis';
import * as nodemailer from 'nodemailer';

@Injectable()
export class EmailProcessor implements OnModuleInit {
  private readonly logger = new Logger(EmailProcessor.name);
  private readonly queueKey = 'bull:email';
  private transporter: nodemailer.Transporter;
  private running = false;

  constructor(
    private readonly config: ConfigService,
    private readonly redis: RedisService,
  ) {
    this.transporter = nodemailer.createTransport({
      host: this.config.get<string>('SMTP_HOST') || 'localhost',
      port: parseInt(this.config.get<string>('SMTP_PORT') || '1025', 10),
      secure: false,
    });
  }

  async onModuleInit() {
    this.running = true;
    this.processLoop();
    this.logger.log('Email processor started');
  }

  private async processLoop() {
    while (this.running) {
      try {
        const job = await this.redis.client?.brpop(this.queueKey, 5);
        if (job) {
          const data = JSON.parse(job[1]);
          await this.sendEmail(data);
        }
      } catch (err) {
        this.logger.error(`Email processing error: ${err}`);
        await new Promise((r) => setTimeout(r, 5000));
      }
    }
  }

  private async sendEmail(data: {
    to: string;
    subject: string;
    body: string;
    isHtml?: boolean;
  }) {
    try {
      await this.transporter.sendMail({
        from: this.config.get<string>('SMTP_FROM') || 'noreply@chatapp.local',
        to: data.to,
        subject: data.subject,
        [data.isHtml ? 'html' : 'text']: data.body,
      });
      this.logger.log(`Email sent to ${data.to}: ${data.subject}`);
    } catch (err) {
      this.logger.error(`Failed to send email to ${data.to}: ${err}`);
    }
  }

  async enqueue(emailData: any) {
    await this.redis.client?.lpush(this.queueKey, JSON.stringify(emailData));
  }
}