DROP PROCEDURE IF EXISTS `add_to_cart`;
DELIMITER ;;
CREATE PROCEDURE `add_to_cart` (
    IN p_product_id INT,
    IN p_session_id CHAR(64)
)
proc:BEGIN
    IF (SELECT COUNT(session_id) FROM sessions WHERE session_id = LOWER(p_session_id)) = 0 OR p_session_id IS NULL THEN
        SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'add_to_cart: No user logged in';
        LEAVE proc;
    END IF;
    IF (SELECT COUNT(id) FROM products WHERE id = p_product_id) = 0 OR p_product_id IS NULL THEN
        SIGNAL SQLSTATE '45001' SET MESSAGE_TEXT = 'add_to_cart: Product does not exist';
        LEAVE proc;
    END IF;
    SELECT user_id INTO @user_id FROM sessions WHERE session_id = LOWER(p_session_id);
    IF (SELECT COUNT(quantity) FROM cart WHERE user_id = @user_id AND product_id = p_product_id) = 0 THEN
        INSERT INTO cart VALUES (@user_id, p_product_id, 1);
    ELSE
        UPDATE cart SET quantity = quantity + 1 WHERE user_id = @user_id AND product_id = p_product_id;
    END IF;
    SELECT 0 AS 'status', 'add_to_cart' AS 'proc';
END ;;
DELIMITER ;
