DROP PROCEDURE IF EXISTS `remove_image_from_product_gallery`;
DELIMITER ;;
CREATE PROCEDURE `remove_image_from_product_gallery` (
    IN p_gallery_id INT,
    IN p_product_id INT,
    IN p_session_id CHAR(64)
)
proc:BEGIN
    DECLARE v_ret INT;
    DECLARE v_user_id INT;
    -- Get user_id associated with the session (implicitly checks if user is logged in)
    CALL get_user_from_session(p_session_id, v_user_id);
    IF v_user_id = -1 THEN
        SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'remove_image_from_product_gallery: No user logged in';
        LEAVE proc;
    END IF;
    -- Check if product belongs to user (implicitly checks if product exists)
    CALL check_if_product_belong_to_user(p_product_id, v_user_id, v_ret);
    IF v_ret != 0 THEN
        SIGNAL SQLSTATE '45001' SET MESSAGE_TEXT = 'remove_image_from_product_gallery: No such product for user';
        LEAVE proc;
    END IF;
    IF (SELECT COUNT(id) FROM product_gallery WHERE id = p_gallery_id AND product_id = p_product_id) = 0 OR p_gallery_id IS NULL THEN
        SIGNAL SQLSTATE '45002' SET MESSAGE_TEXT = 'remove_image_from_product_gallery: No such image for product';
        LEAVE proc;
    END IF;
    -- Remove image from product's gallery
    DELETE FROM product_gallery WHERE id = p_gallery_id AND product_id = p_product_id;
    SELECT 0 AS 'status', 'remove_image_from_product_gallery' AS 'proc';
END ;;
DELIMITER ;
