using System.Net.Mail;
using System.Text;
using IWS5.Core.Models;

namespace IWS5.Services.Helpers;

internal static class MailSender
{
    internal static bool SendEmail(MailTask mailTask, string host, string userName, string password)
    {
        var mySmtpClient = new SmtpClient(host, 25)
        {
            DeliveryMethod = SmtpDeliveryMethod.Network,
            UseDefaultCredentials = false,
            Credentials = new System.Net.NetworkCredential(userName.Trim(), password.Trim()),
            EnableSsl = true
        };

        var from = new MailAddress(mailTask.From);
        var replyTo = new MailAddress(mailTask.ReplyTo);

        foreach (var mailRecipient in mailTask.Recipients)
        {
            var to = new MailAddress(mailRecipient);
            var myMail = new MailMessage(from, to)
            {
                Priority = mailTask.Priority,
                ReplyToList = { replyTo },
                Subject = mailTask.Subject,
                SubjectEncoding = Encoding.UTF8,
                Body = mailTask.Message,
                BodyEncoding = Encoding.UTF8,
                IsBodyHtml = true
            };

            foreach (var ccItem in mailTask.CC)
            {
                if (!string.IsNullOrWhiteSpace(ccItem))
                    myMail.CC.Add(new MailAddress(ccItem));
            }

            foreach (var bccItem in mailTask.BCC)
            {
                if (!string.IsNullOrWhiteSpace(bccItem))
                    myMail.Bcc.Add(new MailAddress(bccItem));
            }

            mySmtpClient.Send(myMail);
        }

        return true;
    }
}