const { processReminder } = require("./handler");
const { logger } = require("../shared");

/**
 * Lambda handler for condition check reminder emails.
 *
 * Invoked by EventBridge Scheduler with a payload containing:
 * - rentalId: UUID of the rental
 * - checkType: Type of check (pre_rental_owner, rental_start_renter, rental_end_renter, post_rental_owner)
 * - scheduleName: Name of the schedule (for cleanup after execution)
 *
 * @param {Object} event - EventBridge Scheduler event
 * @returns {Promise<Object>} Result of the reminder processing
 */
exports.handler = async (event) => {
  logger.info("Lambda invoked", { event });

  // Extract payload - EventBridge Scheduler sends it directly
  const { rentalId, checkType, scheduleName } = event;

  // Validate required fields
  if (!rentalId) {
    logger.error("Missing rentalId in event payload");
    return {
      statusCode: 400,
      body: JSON.stringify({ error: "Missing rentalId" }),
    };
  }

  if (!checkType) {
    logger.error("Missing checkType in event payload");
    return {
      statusCode: 400,
      body: JSON.stringify({ error: "Missing checkType" }),
    };
  }

  // Validate checkType
  const validCheckTypes = [
    "pre_rental_owner",
    "rental_start_renter",
    "rental_end_renter",
    "post_rental_owner",
  ];

  if (!validCheckTypes.includes(checkType)) {
    logger.error("Invalid checkType", { checkType, validCheckTypes });
    return {
      statusCode: 400,
      body: JSON.stringify({ error: "Invalid checkType" }),
    };
  }

  // Process the reminder
  const result = await processReminder(rentalId, checkType, scheduleName);

  if (result.success) {
    return {
      statusCode: 200,
      body: JSON.stringify(result),
    };
  } else {
    return {
      statusCode: 500,
      body: JSON.stringify(result),
    };
  }
};
