DROP PROCEDURE IF EXISTS GenerateNotifications;
CREATE PROCEDURE GenerateNotifications(NumRows integer)
LANGUAGE plpgsql
AS $$
    DECLARE
        i integer := 1;
        minUserId integer;
        maxUserId integer;
        createdStart integer := EXTRACT('epoch' FROM timestamp 'now') - NumRows;
        readStart integer := EXTRACT('epoch' FROM timestamp 'tomorrow') - NumRows;
        timeCreated integer;
        timeRead integer;
    BEGIN
        SELECT MIN(id) INTO minUserId FROM mdl_user;
        SELECT MAX(id) INTO maxUserId FROM mdl_user;
        WHILE i < NumRows LOOP
            IF i % 4 = 0 THEN
                timeRead := readStart + ((i / 40) * 40);
            ELSE
                timeRead := NULL;
            END IF;
            timeCreated := createdStart + ((i / 10) * 10);
            INSERT INTO mdl_notifications (useridfrom, useridto, subject, fullmessage, fullmessagehtml, smallmessage, component, eventtype, contexturl, contexturlname, timeread, timecreated, customdata)
                VALUES (
                    FLOOR(minUserId + random() *  (maxUserId - minUserId)),
                    FLOOR(minUserId + random() *  (maxUserId - minUserId)),
                    CONCAT('Message subject ', i),
                    CONCAT('Full message ', i),
                    CONCAT('<p>Full message</p> ', i),
                    CONCAT('small message', i),
                    'core',
                    'notification',
                    'http://example.com',
                    'example',
                    timeRead,
                    timeCreated,
                    '{"foo":"bar"}'
                );
            i := i + 1;
        END LOOP;
    END;
$$;

CALL GenerateNotifications(4000000);
