const EmailClient = require("../core/EmailClient");
const TemplateManager = require("../core/TemplateManager");
const logger = require("../../../utils/logger");

/**
 * RentalReminderEmailService handles rental reminder emails
 * This service is responsible for:
 * - Sending condition check reminders
 */
class RentalReminderEmailService {
  constructor() {
    this.emailClient = new EmailClient();
    this.templateManager = new TemplateManager();
    this.initialized = false;
  }

  /**
   * Initialize the rental reminder email service
   * @returns {Promise<void>}
   */
  async initialize() {
    if (this.initialized) return;

    await Promise.all([
      this.emailClient.initialize(),
      this.templateManager.initialize(),
    ]);

    this.initialized = true;
    logger.info("Rental Reminder Email Service initialized successfully");
  }

  /**
   * Send condition check reminder email
   * @param {string} userEmail - User's email address
   * @param {Object} notification - Notification object
   * @param {string} notification.title - Notification title
   * @param {string} notification.message - Notification message
   * @param {Object} notification.metadata - Notification metadata
   * @param {string} notification.metadata.deadline - Condition check deadline
   * @param {Object} rental - Rental object
   * @param {Object} rental.item - Item object
   * @param {string} rental.item.name - Item name
   * @returns {Promise<{success: boolean, messageId?: string, error?: string}>}
   */
  async sendConditionCheckReminder(userEmail, notification, rental) {
    if (!this.initialized) {
      await this.initialize();
    }

    try {
      const variables = {
        title: notification.title,
        message: notification.message,
        itemName: rental?.item?.name || "Unknown Item",
        deadline: notification.metadata?.deadline
          ? new Date(notification.metadata.deadline).toLocaleDateString()
          : "Not specified",
      };

      const htmlContent = await this.templateManager.renderTemplate(
        "conditionCheckReminderToUser",
        variables
      );

      return await this.emailClient.sendEmail(
        userEmail,
        `Village Share: ${notification.title}`,
        htmlContent
      );
    } catch (error) {
      logger.error("Failed to send condition check reminder:", error);
      return { success: false, error: error.message };
    }
  }
}

module.exports = RentalReminderEmailService;
