using System.Text;
using System.Text.Json;
namespace Cleanuparr.Infrastructure.Features.Notifications;
///
/// Shared HTTP send mechanics for the JSON-based notification proxies: serialization, tracing,
/// dispatch and status-code-to-exception mapping.
///
public static class NotificationHttpSender
{
private const string DefaultErrorMessage = "Unable to send notification";
///
/// Serializes onto and sends it, translating
/// any into a provider-specific exception via
/// and .
///
/// The client used to send the request.
/// The request to send; its is set by this method.
/// The payload to serialize as the request body.
/// The JSON options to serialize with.
/// Optional callback invoked with the serialized payload before sending, for trace logging.
/// Builds the provider-specific exception from a message and an optional inner exception.
/// Maps an HTTP status code to the message and whether to include the inner exception.
public static async Task SendAsync(
HttpClient httpClient,
HttpRequestMessage request,
TPayload payload,
JsonSerializerOptions serializerOptions,
Action? logTrace,
Func exceptionFactory,
IReadOnlyDictionary statusCodeMessages)
{
try
{
string content = JsonSerializer.Serialize(payload, serializerOptions);
logTrace?.Invoke(content);
request.Content = new StringContent(content, Encoding.UTF8, "application/json");
using HttpResponseMessage response = await httpClient.SendAsync(request);
response.EnsureSuccessStatusCode();
}
catch (HttpRequestException exception)
{
if (exception.StatusCode is null)
{
throw exceptionFactory(DefaultErrorMessage, exception);
}
if (statusCodeMessages.TryGetValue((int)exception.StatusCode, out (string Message, bool IncludeException) entry))
{
throw exceptionFactory(entry.Message, entry.IncludeException ? exception : null);
}
throw exceptionFactory(DefaultErrorMessage, exception);
}
}
}