USE `gateguard`;

DROP PROCEDURE IF EXISTS `sp_createVisitorTypes`;

DELIMITER $$
CREATE PROCEDURE `sp_createVisitorTypes` (
    IN p_NAME VARCHAR(255),
    IN p_DESCRIPTION TEXT,
    IN p_MODIFIED_BY INT,
    OUT v_VISITOR_TYPE_ID INT,
	OUT v_ERROR_CODE VARCHAR(255),
	OUT v_ERROR_MESSAGE VARCHAR(255)
)
BEGIN
    DECLARE EXIT HANDLER FOR SQLEXCEPTION, SQLWARNING
    BEGIN
        GET DIAGNOSTICS CONDITION 1 @sqlstate = RETURNED_SQLSTATE, @errno = MYSQL_ERRNO, @text = MESSAGE_TEXT;
		SET v_ERROR_MESSAGE = @text;
		SET v_ERROR_CODE = CONCAT(@errno, '|', @sqlstate);
		ROLLBACK;
    END;

    SET AUTOCOMMIT=0;
    START TRANSACTION;

    INSERT INTO visitor_types (NAME, DESCRIPTION)
    VALUES (p_NAME, p_DESCRIPTION);

    SET v_VISITOR_TYPE_ID = LAST_INSERT_ID();

    INSERT INTO visitor_types_audit (
        MODIFIED_BY, 
        MODIFIED_ON,  
        MODIFICATION, 
        ID, 
        NAME, 
        DESCRIPTION
    ) VALUES (
        p_MODIFIED_BY,
        SYSDATE(),
        'CREATED',
        v_VISITOR_TYPE_ID,
        p_NAME,
        p_DESCRIPTION
    );

    COMMIT;
END$$
DELIMITER ;
