/* ADDS A NEW EMAIL TO THE EMAIL QUEUE TO BE SENT */
/* =============================================================================================================== */
DROP PROCEDURE IF EXISTS addEmailToQueue;
COMMIT;

DELIMITER //

CREATE PROCEDURE `addEmailToQueue`(`p_email` VARCHAR(255), `p_templateId` INT, `p_due` DATETIME, `p_expire` DATETIME, 
  `p_payload` TEXT)
BEGIN

DECLARE errno INT;
DECLARE iEmail INT;

DECLARE EXIT HANDLER FOR SQLEXCEPTION
BEGIN
	GET CURRENT DIAGNOSTICS CONDITION 1 errno = MYSQL_ERRNO;

	INSERT INTO debug_log(activity, ts_when, log) 
  SELECT 'PROC ERR: loadEmail', NOW(), errno; 

	RESIGNAL;
END;

	INSERT IGNORE INTO `EmailQueue`(`email`, `templateId`, `due`, `expire`, `payload`, `status`, `attempts`, `error`, `sentAt`,
		`createdAt`, `updatedAt`)
	VALUES (p_email, p_templateId, p_due, p_expire, p_payload, 'ready', 0, NULL, NULL, NOW(), NOW());

END
//

COMMIT //

DELIMITER ;

