using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;
using API.Models.Outgoing;
using Microsoft.AspNetCore.Identity.UI.Services;

namespace API.Services;

public class PlunkEmailSender(HttpClient httpClient, string plunkSecretKey) : IEmailSender
{
    public async Task SendEmailAsync(string email, string subject, string htmlMessage)
    {
        var requestBody = new PlunkEmailDto()
        {
            To = email,
            Subject = subject,
            Body = htmlMessage
        };

        var jsonContent = new StringContent(
            JsonSerializer.Serialize(requestBody),
            Encoding.UTF8,
            "application/json"
        );

        httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", plunkSecretKey);

        var response = await httpClient.PostAsync("https://api.useplunk.com/v1/send", jsonContent);

        if (!response.IsSuccessStatusCode)
        {
            var error = await response.Content.ReadAsStringAsync();
            throw new Exception($"Fehler beim Senden der E-Mail über Plunk: {error}");
        }
    }
}