using System.Diagnostics;
using bitforum.Models;
using bitforum.Repository;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using bitforum.Helpers;
using System.Net.Mail;
using System.Net;

namespace bitforum.Controllers.Setting
{
    [Authorize]
    [Route("Setting")]
    public class TestController : Controller
    {
        private readonly ILogger<TestController> _logger;
        private readonly ConfigRepository _configRepository;
        private readonly string _ViewPath = "~/Views/Setting/Test.cshtml";

        public TestController(ILogger<TestController> logger, ConfigRepository configRepository)
        {
            _logger = logger;
            _configRepository = configRepository;
        }

        [HttpGet("Test")]
        public IActionResult Index()
        {
            ViewBag.config = _configRepository.GetAll();

            return View(_ViewPath);
        }

        [HttpPost("Test")]
        public async Task<IActionResult> Send(string? email)
        {
            try
            {
                if (string.IsNullOrEmpty(email))
                {
                    TempData["ErrorMessages"] = "이메일 주소를 입력해주세요.";
                    return RedirectToAction("Index", "Test");
                }

                var config = _configRepository.GetAll();
                var _smtpServer = config.GetConfig("smtp_server");
                var _smtpPort = int.Parse(config.GetConfig("smtp_port"));
                var _fromEmail = config.GetConfig("smtp_from_email");
                var _emailPassword = config.GetConfig("smtp_email_password");

                var client = new SmtpClient(_smtpServer, _smtpPort)
                {
                    Credentials = new NetworkCredential(_fromEmail, _emailPassword),
                    EnableSsl = true
                };

                var mailMessage = new MailMessage
                {
                    From = new MailAddress(_fromEmail),
                    Subject = "Test E-mail",
                    Body = "현재 이메일을 보고 있거나 받았다면 이메일이 정상적으로 수신된 것입니다.",
                    IsBodyHtml = false
                };
                mailMessage.To.Add(email);
                await client.SendMailAsync(mailMessage);

                TempData["SuccessMessage"] = "이메일이 전송되었습니다.";
                return View(_ViewPath);
            }
            catch (SmtpException smtpEx)
            {
                TempData["ErrorMessages"] = smtpEx.Message;
                Console.WriteLine($"SMTP error: {smtpEx.Message}");
                _logger.LogError($"SMTP error: {smtpEx.StatusCode} - {smtpEx.Message}");
                return RedirectToAction("Index", "Test");
            }
            catch (Exception ex)
            {
                TempData["ErrorMessages"] = ex.Message;
                Console.WriteLine($"Email sending failed: {ex.Message}");
                _logger.LogError($"Failed to send email to {email}: {ex.Message}");
                return RedirectToAction("Index", "Test");
            }
        }

        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }
    }
}
