// signup.listener.ts
import { Injectable } from '@nestjs/common';
import { OnEvent } from '@nestjs/event-emitter';
// import { guglu } from 'src/constants/email';
import { getConfig } from 'src/utils/siteconfig';
import { ForgotPasswordEvent } from '../events/forgot-password-event';
import { MailService } from 'src/modules/mail/mail.service';

/**
 * ForgotPasswordListener - Event listener for password reset notifications
 *
 * This listener handles the 'student.forgotPassword' event by sending
 * password reset emails to users who have requested password recovery.
 *
 * Responsibilities:
 * - Sends password reset emails with new password/temporary credentials
 * - Falls back to admin email if student email is unavailable
 * - Uses Handlebars templates for email formatting
 * - Includes password reset instructions or temporary password
 *
 * Event flow:
 * 1. User requests password reset → ForgotPasswordEvent emitted
 * 2. This listener catches the event
 * 3. Email is sent to user with reset instructions
 *
 * Security considerations:
 * - Avoid sending plain text passwords via email (security risk)
 * - Consider sending reset links instead of passwords
 * - Implement rate limiting on reset requests
 * - Log password reset attempts
 *
 * @example
 * // Event emission (in a service)
 * this.eventEmitter.emit('student.forgotPassword', new ForgotPasswordEvent(student, tempPassword));
 *
 * // This listener automatically triggers and sends the email
 */
@Injectable()
export class ForgotPasswordListener {
  constructor(private emailService: MailService) {}

  /**
   * Handles 'student.forgotPassword' events by sending password reset emails
   *
   * Listens for password reset events and sends appropriate email notifications.
   * Falls back to admin email if student email is not available.
   *
   * @param studentDetails - Event containing student data and new password
   *
   * @note Sending plain text passwords via email is a security risk
   *       Consider sending reset links instead of actual passwords
   *
   * @warning Exposing passwords in email is insecure - use temporary reset links
   */
  @OnEvent('student.forgotPassword')
  sendAdminEmail(studentDetails: ForgotPasswordEvent) {
    // Load site configuration for email settings
    const config = getConfig('site');

    // Determine recipient: student email or fallback to admin
    const to = studentDetails?.student?.email ?? config.adminEmail;

    // Extract student name for personalization
    const studentName = studentDetails.student
      ? `${studentDetails.student?.fname} ${studentDetails.student?.lname}`
      : 'User';

    // Send password reset email
    this.emailService.sendEmail(
      config.replyTo, // From address
      to, // To address (student or admin)
      `Forgot Password Reply`, // Email subject
      `${config.template_path}forgotpassword.hbs`, // Template path
      {
        // Template data
        subject: 'Forgot Password Reply',
        url: config.url,
        studentName: studentName,
        // Consider adding: resetLink, expirationTime, supportContact
      },
      // Plain text fallback (insecure: contains plain password)
      `Hi ${studentName}, Your new password is: ${studentDetails.password}`,
    );

    // TODO: Log this password reset attempt for security monitoring
    // console.log(`Password reset email sent to ${to} for student ${studentName}`);
  }
}
