/* ACCEPT A MED BUDDY INVITE FORM A USER */
/* =============================================================================================================== */
DROP PROCEDURE IF EXISTS acceptMedBuddyInvite;
COMMIT;

DELIMITER //

CREATE PROCEDURE `acceptMedBuddyInvite`(`p_buddyId` VARCHAR(36))
BEGIN

DECLARE errno INT;
DECLARE vBuddyStatus VARCHAR(20);

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

  ROLLBACK;

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

	RESIGNAL;
END;

START TRANSACTION;

  SELECT `status`
  FROM `MedBuddies`
  WHERE `_id` = p_buddyId
  INTO vBuddyStatus;

  IF vBuddyStatus IS NULL THEN 
    SIGNAL SQLSTATE '45000'
    SET MESSAGE_TEXT = 'Cannot find your Med Buddy invitation.';
  ELSEIF vBuddyStatus = 'deleted' THEN 
    SIGNAL SQLSTATE '45000'
    SET MESSAGE_TEXT = 'Your invitation is no longer valid.';
  ELSEIF vBuddyStatus = 'cancelled' THEN 
    SIGNAL SQLSTATE '45000'
    SET MESSAGE_TEXT = 'Your invitation has been cancelled.';
  ELSEIF vBuddyStatus = 'active' THEN
    SIGNAL SQLSTATE '45000'
    SET MESSAGE_TEXT = 'Your invitation has already been accepted.';
  ELSEIF vBuddyStatus = 'inactive' THEN 
    SIGNAL SQLSTATE '45000'
    SET MESSAGE_TEXT = 'Your invitation has already expired.';
  END IF;

  UPDATE `MedBuddies`
  SET `status` = 'active',
    `updatedAt` = NOW()
  WHERE `_id` = p_buddyId;

COMMIT WORK;

END
//

COMMIT //

DELIMITER ;

