using MailKit.Net.Smtp;
using MailKit.Security;
using MimeKit;
using Email;
using System.Text;

namespace TechHelper.Features
{
	public class QEmailSender : IEmailSender
	{
		public async Task SendEmailAsync(string toEmail, string subject, string body)
		{
			var secureSocketOption = SecureSocketOptions.StartTls;
			try
			{
				var message = new MimeMessage();
				message.From.Add(new MailboxAddress("TechHelper", EmailConfiguration.EmailFrom));
				message.To.Add(new MailboxAddress("", toEmail));
				message.Subject = subject;
				message.Body = new TextPart(MimeKit.Text.TextFormat.Html)
				{
					Text = body
				};


				using (var client = new SmtpClient())
				{
					await client.ConnectAsync(EmailConfiguration.SmtpHost, EmailConfiguration.SmtpPort, secureSocketOption);

					// 移除 XOAUTH2 认证机制，避免某些环境下出现异常
					// 如果不加这行，某些情况下可能会遇到 MailKit.Security.AuthenticationException: XOAUTH2 is not supported
					client.AuthenticationMechanisms.Remove("XOAUTH2");

					await client.AuthenticateAsync(EmailConfiguration.EmailFrom, EmailConfiguration.Password);
					await client.SendAsync(message);
					await client.DisconnectAsync(true);
				}

				Console.WriteLine("邮件发送成功 (QQ 邮箱)！");
			}
			catch (TypeInitializationException ex)
			{
				Console.WriteLine("捕获到 SmtpClient 的 TypeInitializationException！");
				Console.WriteLine($"异常消息: {ex.Message}");

				Exception? inner = ex.InnerException; // 获取第一层内部异常
				int innerCount = 1;
				while (inner != null)
				{
					Console.WriteLine($"--> 内部异常 {innerCount}: {inner.GetType().Name}");
					Console.WriteLine($"--> 内部异常消息: {inner.Message}");
					inner = inner.InnerException; // 获取下一层内部异常
					innerCount++;
				}
			}
			catch (Exception ex)
			{
				Console.WriteLine($"捕获到其他类型的异常: {ex.GetType().Name}");
				Console.WriteLine($"异常消息: {ex.Message}");
			}
		}

		public async Task SendEmailAsync(string toEmail , string body)
		{
			await SendEmailAsync(toEmail, EmailConfiguration.SubDescribe, body);
		}

		public async Task SendEmailAuthcodeAsync(string toEmail, string authCode)
		{
			string htmlTemplateString = EmailTemap._email;
			string htmlBody = htmlTemplateString
								.Replace("{{AppName}}", "TechHelper")
								.Replace("{{VerificationCode}}", authCode)
								.Replace("{{ExpirationMinutes}}", "30")
								.Replace("{{SupportEmail}}", "TechHelper");
			await SendEmailAsync(toEmail, htmlBody);
		}
	}
}
