CREATE OR ALTER PROCEDURE dbo.GenerateNotifications
@NumRows INT
AS
BEGIN
    DECLARE
        @i INT = 1,
        @minUserId INT,
        @maxUserId INT,
        @createdStart INT,
        @readStart INT,
        @timeCreated INT,
        @timeRead INT;

    -- Calculate timestamp values
    SELECT
            @minUserId = MIN(id),
            @maxUserId = MAX(id),
            @createdStart = CAST(DATEDIFF(SECOND, '1970-01-01', GETUTCDATE()) AS INT) - @NumRows,
            @readStart = CAST(DATEDIFF(SECOND, '1970-01-01', GETUTCDATE() + 1) AS INT) - @NumRows
    FROM
        mdl_user;

    -- Loop to generate and insert notifications
    WHILE @i < @NumRows
    BEGIN
        -- Conditional timeRead calculation
        IF @i % 4 = 0
            SET @timeRead = @readStart + ((@i / 40) * 40);
        ELSE
            SET @timeRead = NULL;

        -- TimeCreated calculation
        SET @timeCreated = @createdStart + ((@i / 10) * 10);

        -- Insert into mdl_notifications
        INSERT INTO mdl_notifications (
            useridfrom,
            useridto,
            subject,
            fullmessage,
            fullmessagehtml,
            smallmessage,
            component,
            eventtype,
            contexturl,
            contexturlname,
            timeread,
            timecreated,
            customdata
        )
        VALUES (
           FLOOR(@minUserId + RAND() * (@maxUserId - @minUserId)),
           FLOOR(@minUserId + RAND() * (@maxUserId - @minUserId)),
           'Message subject ' + CAST(@i AS NVARCHAR(MAX)),
           'Full message ' + CAST(@i AS NVARCHAR(MAX)),
           '<p>Full message</p> ' + CAST(@i AS NVARCHAR(MAX)),
           'small message' + CAST(@i AS NVARCHAR(MAX)),
           'core',
           'notification',
           'http://example.com',
           'example',
           @timeRead,
           @timeCreated,
           '{"foo":"bar"}'
       );

        -- Increment loop counter
        SET @i = @i + 1;
    END;
END;

EXEC GenerateNotifications @NumRows = 4000000;
