DECLARE
@RowLimit INT = IIF(@Limit IS NULL OR @Limit <= 0, 100, @Limit);

SELECT *
FROM [dbo].[AgentMemories]
WHERE [WorkspaceId] = @WorkspaceId
  AND (@AgentId IS NULL
   OR [AgentId] = @AgentId)
  AND (
    @Search IS NULL
   OR
    [Summary] LIKE N'%' + @Search + N'%'
   OR
    [Content] LIKE N'%' + @Search + N'%'
    )
  AND (
    @Tag IS NULL
   OR EXISTS (SELECT 1
    FROM OPENJSON([TagsJson])
    WHERE value = @Tag)
    )
ORDER BY [UpdatedUtc] DESC
OFFSET 0 ROWS FETCH NEXT @RowLimit ROWS ONLY;
