using MailKit.Net.Smtp;
using MailKit.Security;
using MimeKit;

namespace ROLAC.API.Services.Notifications;

/// <summary>Sends a single email via MailKit using the current (DB-backed) SMTP settings.</summary>
public sealed class MailKitSmtpDispatcher : ISmtpDispatcher
{
    private readonly INotificationSettingsService _settings;

    public MailKitSmtpDispatcher(INotificationSettingsService settings) => _settings = settings;

    public async Task SendAsync(OutboundEmail email, CancellationToken ct = default)
    {
        var options = _settings.GetSmtp();

        var message = new MimeMessage();
        message.From.Add(new MailboxAddress(options.FromName, options.FromAddress));
        message.To.Add(MailboxAddress.Parse(email.ToAddress));
        message.Subject = email.Subject;

        var builder = new BodyBuilder { HtmlBody = email.HtmlBody };
        foreach (var attachment in email.Attachments)
        {
            builder.Attachments.Add(
                attachment.FileName, attachment.Content, ContentType.Parse(attachment.ContentType));
        }
        message.Body = builder.ToMessageBody();

        using var client = new SmtpClient();
        var socketOptions = options.UseSsl ? SecureSocketOptions.StartTls : SecureSocketOptions.Auto;
        await client.ConnectAsync(options.Host, options.Port, socketOptions, ct);
        if (!string.IsNullOrEmpty(options.User))
            await client.AuthenticateAsync(options.User, options.Password, ct);
        await client.SendAsync(message, ct);
        await client.DisconnectAsync(true, ct);
    }
}
