DELIMITER $$

CREATE PROCEDURE `up_and_down`.`fill_treatment_schemes`()
BEGIN
    DECLARE done INT DEFAULT 0;
    DECLARE v_uts_uuid CHAR(36);
    DECLARE v_user_uuid CHAR(36);
    DECLARE v_count INT;
    DECLARE v_i INT;
    DECLARE v_med_uuid CHAR(36);

    -- курсор по всем схемам лечения пользователей
    DECLARE cur CURSOR FOR
SELECT uuid, user_uuid
FROM `up_and_down`.`user_treatment_schemes`;

DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;

OPEN cur;

read_loop: LOOP
        FETCH cur INTO v_uts_uuid, v_user_uuid;
        IF done = 1 THEN
            LEAVE read_loop;
END IF;

        -- случайное количество препаратов от 1 до 5
        SET v_count = FLOOR(RAND() * 5) + 1;
        SET v_i = 0;

        meds_loop: WHILE v_i < v_count DO
            -- случайный препарат из уже существующих medications
SELECT m.uuid
INTO v_med_uuid
FROM `up_and_down`.`medications` m
ORDER BY RAND()
    LIMIT 1;

-- чтобы не было дублей (один и тот же препарат в одной схеме)
IF NOT EXISTS (
                SELECT 1
                FROM `up_and_down`.`treatment_schemes` ts
                WHERE ts.user_treatment_schemes_uuid = v_uts_uuid
                  AND ts.medication_uuid = v_med_uuid
            ) THEN
                INSERT INTO `up_and_down`.`treatment_schemes` (
                    `user_treatment_schemes_uuid`,
                    `medication_uuid`
                ) VALUES (
                    v_uts_uuid,
                    v_med_uuid
                );
                SET v_i = v_i + 1;
END IF;
END WHILE;
END LOOP;

CLOSE cur;
END$$

DELIMITER ;

CALL `up_and_down`.`fill_treatment_schemes`();
