MERGE [dbo].[ReviewerFeedbackInsights] AS T
    USING (VALUES (@WorkspaceId, @Reviewer, @WindowDate, @EventCount, @HighSeverityCount, @ActionableCount, @LastEventAt,
    @LastEventSummary, @LastEventId))
    AS S([WorkspaceId], [Reviewer], [WindowDate], [EventCount], [HighSeverityCount], [ActionableCount], [LastEventAt],
    [LastEventSummary], [LastEventId])
    ON T.[WorkspaceId] = S.[WorkspaceId]
    AND T.[Reviewer] = S.[Reviewer]
    AND T.[WindowDate] = S.[WindowDate]
    WHEN MATCHED THEN
UPDATE
    SET T.[EventCount] = T.[EventCount] + S.[EventCount],
    T.[HighSeverityCount] = T.[HighSeverityCount] + S.[HighSeverityCount],
    T.[ActionableCount] = T.[ActionableCount] + S.[ActionableCount],
    T.[LastEventAt] = CASE
    WHEN S.[LastEventAt] >= T.[LastEventAt] THEN S.[LastEventAt]
    ELSE T.[LastEventAt]
END
,
        T.[LastEventSummary]  = CASE
                                    WHEN S.[LastEventAt] >= T.[LastEventAt] THEN S.[LastEventSummary]
                                    ELSE T.[LastEventSummary]
END
,
        T.[LastEventId]       = CASE
                                    WHEN S.[LastEventAt] >= T.[LastEventAt] THEN S.[LastEventId]
                                    ELSE T.[LastEventId]
END
WHEN NOT MATCHED THEN
    INSERT ([WorkspaceId], [Reviewer], [WindowDate], [EventCount], [HighSeverityCount], [ActionableCount],
            [LastEventAt], [LastEventSummary], [LastEventId])
    VALUES (S.[WorkspaceId], S.[Reviewer], S.[WindowDate], S.[EventCount], S.[HighSeverityCount], S.[ActionableCount],
            S.[LastEventAt], S.[LastEventSummary], S.[LastEventId]);
