DROP PROCEDURE IF EXISTS `update_cart`;
DELIMITER ;;
CREATE PROCEDURE `update_cart` (
    IN p_product_id INT,
    IN p_quantity INT UNSIGNED,
    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 = 'update_cart: No user logged in';
        LEAVE proc;
    END IF;
    SELECT user_id INTO @user_id FROM sessions WHERE session_id = LOWER(p_session_id);
    IF (SELECT COUNT(product_id) FROM cart WHERE user_id = @user_id) = 0 OR p_product_id IS NULL THEN
        SIGNAL SQLSTATE '45001' SET MESSAGE_TEXT = 'update_cart: Item does not exist in cart';
        LEAVE proc;
    END IF;
    IF p_quantity > (SELECT stock FROM products WHERE id = p_product_id) THEN
        SIGNAL SQLSTATE '45002' SET MESSAGE_TEXT = 'update_cart: Maximum quantity reached';
        LEAVE proc;
    END IF;
    UPDATE cart SET quantity = p_quantity WHERE user_id = @user_id AND product_id = p_product_id;
    SELECT 0 AS 'status', 'update_cart' AS 'proc';
END ;;
DELIMITER ;
