import { Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import * as nodemailer from 'nodemailer';

/**
 * MailService — sends transactional emails (OTP verification, password reset).
 * When SMTP_HOST is not configured, logs the code to the console for development.
 */
@Injectable()
export class MailService {
  constructor(private readonly config: ConfigService) {}

  async sendOtp(to: string, code: string, subject: string): Promise<void> {
    const smtpHost = this.config.get<string>('SMTP_HOST');

    // Dev mode: log to console instead of sending
    if (!smtpHost) {
      console.log(`[MAIL] To: ${to} | Subject: ${subject} | OTP code: ${code}`);
      return;
    }

    const transporter = nodemailer.createTransport({
      host: smtpHost,
      port: this.config.get<number>('SMTP_PORT', 587),
      auth: {
        user: this.config.get<string>('SMTP_USER'),
        pass: this.config.get<string>('SMTP_PASS'),
      },
    });

    await transporter.sendMail({
      from: this.config.get<string>('SMTP_FROM', 'noreply@lexibrain.app'),
      to,
      subject,
      text: `Your LexiBrain code is: ${code}\n\nThis code expires in 15 minutes.`,
    });
  }
}
