DROP PROCEDURE IF EXISTS `add_image_to_product_gallery`;
DELIMITER ;;
CREATE PROCEDURE `add_image_to_product_gallery` (
    IN p_product_id INT,
    IN p_filename VARCHAR(100),
    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 = 'add_image_to_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 = 'add_image_to_product_gallery: No such product for user';
        LEAVE proc;
    END IF;
    -- Add image to product's gallery
    INSERT INTO product_gallery (`product_id`, `filename`) VALUES (p_product_id, p_filename);
    SELECT 0 AS 'status';
END ;;
DELIMITER ;
