DROP PROCEDURE IF EXISTS `add_product_to_order`;
DELIMITER ;;
CREATE PROCEDURE `add_product_to_order` (
    IN p_product_id INT,
    IN p_quantity INT,
    IN p_order_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_product_to_order: 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(id) FROM orders WHERE id = p_order_id AND buyer_id = @user_id) = 0 OR p_order_id IS NULL THEN
        SIGNAL SQLSTATE '45001' SET MESSAGE_TEXT = 'add_product_to_order: Order does not exist';
        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 '45002' SET MESSAGE_TEXT = 'add_product_to_order: Product does not exist';
        LEAVE proc;
    END IF;
    SELECT price INTO @price FROM products WHERE id = p_product_id;
    UPDATE products SET stock = stock - p_quantity WHERE id = p_product_id;
    INSERT INTO order_products VALUES (p_order_id, p_product_id, p_quantity, @price*p_quantity);
    SELECT 0 AS 'status', 'add_product_to_order' AS 'proc';
END ;;
DELIMITER ;
