/* SYNC USER ACCOUNT AND PROFILES */
/* =============================================================================================================== */
DROP PROCEDURE IF EXISTS synchroniseUserAccountAndProfiles;
COMMIT;

DELIMITER //

CREATE PROCEDURE `synchroniseUserAccountAndProfiles`(`p_userId` BIGINT, `p_pushToken` VARCHAR(255))

BEGIN

DECLARE errno INT;
DECLARE iIsAccountDeleted INT;

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: gUserProf', NOW(), errno; 

  RESIGNAL;
END;

START TRANSACTION;

  SELECT COUNT(*)
  FROM `DeletedUsers`
  WHERE `_id` = p_userId
  INTO iIsAccountDeleted;

  IF iIsAccountDeleted IS NULL OR iIsAccountDeleted > 0 THEN
    SIGNAL SQLSTATE '45000'
    SET MESSAGE_TEXT = 'This account has been deleted.';
  END IF;

  IF p_pushToken IS NOT NULL THEN
    UPDATE `Users`
    SET `pushToken` = p_pushToken,
      `updatedAt` = NOW()
    WHERE `_id` = p_userId
    AND `status` = 'active'
    AND `pushToken` != p_pushToken;
  END IF;

  /* User data */
  SELECT `_id`, `name`, `surname`, `email`, `mobileNumber`, `gender`, `termsAccepted`, `country`,
    IF(`dateOfBirth` IS NULL, NULL, DATE_FORMAT(`dateOfBirth`, '%Y-%m-%d')) as `dateOfBirth`, `pushToken`
  FROM `Users` 
  WHERE `_id` = p_userId;

  /* Dependant data */
  SELECT `_id`, `name`, `gender`, DATE_FORMAT(`dateOfBirth`, '%Y-%m-%d') AS `dateOfBirth`
  FROM `Dependants`
  WHERE `userId` = p_userId
  AND `status` = 'active';

  /* Med-buddy data */
  SELECT `_id`, `name`, `email`, `shareMeds`, `status`
  FROM `MedBuddies`
  WHERE `userId` = p_userId
  AND `status` IN ('active', 'pending');

COMMIT WORK;

END
//

COMMIT //

DELIMITER ;
