using bitforum.Repository;
using Microsoft.AspNetCore.Identity.UI.Services;
using System.Net;
using System.Net.Mail;

namespace bitforum.Services
{
    public class EmailSender : IEmailSender
    {
        private readonly ILogger _logger;
        private readonly ConfigRepository _configRepository;

        private readonly string _smtpServer;
        private readonly int _smtpPort;
        private readonly string _fromEmail;
        private readonly string _emailPassword;

        public EmailSender(IConfiguration configuration, ILogger<EmailSender> logger, ConfigRepository configRepository)
        {
            _configRepository = configRepository;
            _logger = logger;

            // 1차로 Config 값 SMTP 조회
            _smtpServer = _configRepository.GetByKey("smtp_server")?.Value ?? string.Empty;
            _smtpPort = int.TryParse(_configRepository.GetByKey("smtp_port")?.Value, out var port) ? port : 0;
            _fromEmail = _configRepository.GetByKey("smtp_from_email")?.Value ?? string.Empty;
            _emailPassword = _configRepository.GetByKey("smtp_email_password")?.Value ?? string.Empty;


            // 2차로 appsettings.json 값 SMTP 조회
            var emailSettings = configuration.GetSection("EmailSettings");

            if (string.IsNullOrEmpty(_smtpServer))
            {
                _smtpServer = emailSettings["SmtpServer"] ?? string.Empty;
            }
            if (_smtpPort <= 0)
            {
                _smtpPort = int.TryParse(emailSettings["SmtpPort"], out var smtpPort) ? smtpPort : 0;
            }
            if (string.IsNullOrEmpty(_fromEmail))
            {
                _fromEmail = emailSettings["FromEmail"] ?? string.Empty;
            }
            if (string.IsNullOrEmpty(_emailPassword))
            {
                _emailPassword = emailSettings["EmailPassword"] ?? string.Empty;
            }
        }

        public async Task SendEmailAsync(string email, string subject, string message)
        {
            try
            {
                var client = new SmtpClient(_smtpServer, _smtpPort)
                {
                    Credentials = new NetworkCredential(_fromEmail, _emailPassword),
                    EnableSsl = true
                };

                var mailMessage = new MailMessage
                {
                    From = new MailAddress(_fromEmail),
                    Subject = subject,
                    Body = message,
                    IsBodyHtml = true
                };
                mailMessage.To.Add(email);

                _logger.LogInformation($"Sending email to {email} with subject {subject}.");
                await client.SendMailAsync(mailMessage);
                _logger.LogInformation($"Email sent successfully to {email}.");
            }
            catch (SmtpException smtpEx)
            {
                Console.WriteLine($"SMTP error: {smtpEx.Message}");
                _logger.LogError($"SMTP error: {smtpEx.StatusCode} - {smtpEx.Message}");
                throw;
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Email sending failed: {ex.Message}");
                _logger.LogError($"Failed to send email to {email}: {ex.Message}");
                throw;
            }
        }
    }
}
