using Microsoft.Extensions.Options;
using System.Net.Http.Headers;
using System.Text;

namespace Indotalent.Infrastructure.Email.Mailgun;

public class MailgunEmailSender : IEmailSender
{
    private readonly MailgunSettingsModel _settings;
    private readonly HttpClient _httpClient;

    public MailgunEmailSender(IOptions<EmailSettingsModel> emailOptions, HttpClient httpClient)
    {
        _settings = emailOptions.Value.Mailgun;
        _httpClient = httpClient;
    }

    public async Task SendEmailAsync(string email, string subject, string htmlMessage)
    {
        if (string.IsNullOrEmpty(_settings.ApiKey) || string.IsNullOrEmpty(_settings.Domain))
        {
            throw new Exception("Mailgun configuration is missing ApiKey or Domain.");
        }

        var authToken = Encoding.ASCII.GetBytes($"api:{_settings.ApiKey}");
        _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(authToken));

        var formContent = new FormUrlEncodedContent(new[]
        {
            new KeyValuePair<string, string>("from", _settings.FromEmail),
            new KeyValuePair<string, string>("to", email),
            new KeyValuePair<string, string>("subject", subject),
            new KeyValuePair<string, string>("html", htmlMessage)
        });

        var response = await _httpClient.PostAsync($"https://api.mailgun.net/v3/{_settings.Domain}/messages", formContent);

        if (!response.IsSuccessStatusCode)
        {
            var errorBody = await response.Content.ReadAsStringAsync();
            throw new Exception($"Failed to send email via Mailgun. Status: {response.StatusCode}, Error: {errorBody}");
        }
    }
}