using System;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using Emails.Transactional.Client.Exceptions;
using RestSharp;
namespace Emails.Transactional.Client
{
///
/// Contains extension methods to send emails on remote transational email servers
///
public static class ClientExtensions
{
private const Method DEFAULT_SEND_METHOD = Method.Post;
///
/// Asynchronously begins an email transaction against the mail server with the specified
/// transaction request.
///
///
/// The to submit
/// A cancelaion token to cancel the operation
/// A task that represents the async send operation
///
///
///
///
public static async Task SendEmailAsync(this RestClient client, EmailTransactionRequest transaction, CancellationToken token = default)
{
//Init the new request
RestRequest request = new(transaction.Endpoint, DEFAULT_SEND_METHOD)
{
//Json request
RequestFormat = DataFormat.Json
};
//add/serialze the transacion request
request.AddJsonBody(transaction);
//Exec the tranasction on the client
RestResponse response = await client.ExecuteAsync(request, token);
//parse the response body
return response.StatusCode switch
{
HttpStatusCode.Unauthorized or HttpStatusCode.Forbidden => throw new InvalidAuthorizationException("The server did not accept the current authorization", response),
HttpStatusCode.BadRequest => throw new InvalidTransactionRequestException(response),
HttpStatusCode.UnprocessableEntity => throw new ValidationFailedException(response.Data),
HttpStatusCode.OK => response.Data,
_ => throw new InvalidTransactionResponseException("Unhandled status code", response),
};
}
}
}