using KiMailOrderAgent.Models;
using KiMailOrderAgent.Settings;
using MailKit.Net.Smtp;
using MailKit.Security;
using Microsoft.Extensions.Options;
using MimeKit;

namespace KiMailOrderAgent.Approval;

public class EmailApprovalNotifier : IApprovalNotifier
{
    private readonly ApprovalSettings _settings;

    public EmailApprovalNotifier(IOptions<ApprovalSettings> options)
    {
        _settings = options.Value;
    }

    public async Task SendApprovalRequestAsync(
        ExtractedOrder order,
        string message,
        CancellationToken cancellationToken)
    {
        var email = new MimeMessage();

        email.From.Add(MailboxAddress.Parse(_settings.FromEmail));
        email.To.Add(MailboxAddress.Parse(_settings.ToEmail));
        email.Subject = $"Freigabe benötigt [{order.Id}]: Bestellung von {order.Customer.CompanyName ?? order.OriginalMailFrom}";

        email.Body = new TextPart("plain")
        {
            Text = message
        };

        using var client = new SmtpClient();

        await client.ConnectAsync(
            _settings.SmtpHost,
            _settings.SmtpPort,
            SecureSocketOptions.StartTls,
            cancellationToken);

        await client.AuthenticateAsync(
            _settings.SmtpUsername,
            _settings.SmtpPassword,
            cancellationToken);

        await client.SendAsync(email, cancellationToken);
        await client.DisconnectAsync(true, cancellationToken);
    }
}