DROP PROCEDURE IF EXISTS authoriseProvider;
COMMIT;

DELIMITER //

CREATE PROCEDURE `authoriseProvider`(`p_providerId` BIGINT)

BEGIN

DECLARE errno INT;
DECLARE t_shouldKeyUpdate TINYINT DEFAULT NULL;

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

	INSERT INTO debug_log(activity, ts_when, log) 
  SELECT 'PROCERR:authProvider', NOW(), errno; 

  RESIGNAL;
END;

START TRANSACTION;

  SELECT `keyExpireInterval` IS NOT NULL
  FROM `Providers`
  WHERE `_id` = p_providerId
  INTO t_shouldKeyUpdate;

  IF t_shouldKeyUpdate = 1 THEN
    UPDATE `Providers`
    SET `key` = UUID(),
      `keyExpireAt` = DATE_ADD(NOW(), INTERVAL `keyExpireInterval` MINUTE),
      `updatedAt` = NOW()
    WHERE `_id` = p_providerId;
  END IF;

  SELECT `key`
  FROM `Providers`
  WHERE `_id` = p_providerId;

COMMIT WORK;

END 
//

COMMIT //

DELIMITER ;
