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

namespace Indotalent.Infrastructure.Email.Mailjet;

public class MailjetEmailSender : IEmailSender
{
    private readonly MailjetSettingsModel _settings;
    private readonly HttpClient _httpClient;

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

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

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

        var payload = new
        {
            Messages = new[]
            {
                new
                {
                    From = new { Email = _settings.FromEmail, Name = "Mailjet System" },
                    To = new[] { new { Email = email } },
                    Subject = subject,
                    HTMLPart = htmlMessage
                }
            }
        };

        var content = new StringContent(JsonSerializer.Serialize(payload), Encoding.UTF8, "application/json");
        var response = await _httpClient.PostAsync("https://api.mailjet.com/v3.1/send", content);

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