Magento 2 – How to redirect to the last valid page when changing items per page in search results?

I’m facing an issue with my Magento 2 store when adjusting the number of items per page in search results.

I have a search that returns 16 items.
The initial items-per-page setting is 12, so there are two pages of results.
When I navigate to the second page and then change the items-per-page setting to 24, Magento tries to load the second page, which causes an error since, with 24 items per page, there’s only one page of results.

Magento retains the current page (in this case, the second page) even after the items-per-page setting is changed. When the new setting results in fewer pages (e.g., 24 items per page in this example), it attempts to load a non-existent page, causing an error.

I would like Magento to automatically redirect to the last valid page whenever the items-per-page setting is changed, rather than attempting to load a non-existent page.

Is there a way to implement this logic in Magento 2, either through configuration or customization, to ensure the system always navigates to the last valid page when the items-per-page setting is changed? Any guidance on where to make this modification (JavaScript, PHP, etc.) would be very helpful.