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

namespace Indotalent.Infrastructure.Email.SendGrid;

public class SendGridEmailSender : IEmailSender
{
    private readonly SendGridSettingsModel _settings;
    private readonly HttpClient _httpClient;

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

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

        _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", _settings.ApiKey);

        var payload = new
        {
            personalizations = new[]
            {
                new
                {
                    to = new[] { new { email = email } }
                }
            },
            from = new { email = _settings.FromEmail, name = "SendGrid System" },
            subject = subject,
            content = new[]
            {
                new
                {
                    type = "text/html",
                    value = htmlMessage
                }
            }
        };

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

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