using System.Diagnostics;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization;
using bitforum.Models;
using bitforum.Repository;
using bitforum.Services;

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

        public TestController(ILogger<TestController> logger, IConfigRepository configRepository, IMailService mailService)
        {
            _logger = logger;
            _configRepository = configRepository;
            _mailService = mailService;
        }

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

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

            return View(_ViewPath);
        }

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

                string subject = "Test E-mail";
                string content = "현재 이메일을 보고 있거나 받았다면 이메일이 정상적으로 수신된 것입니다.";

                await _mailService.SendEmailAsync(new SendData
                {
                    ToAddress = toAddress,
                    Subject = subject,
                    Message = content
                });

                string message = "이메일이 전송되었습니다.";
                TempData["SuccessMessage"] = message;
                _logger.LogInformation(message);
            }
            catch (Exception e)
            {
                TempData["ErrorMessages"] = e.Message;
                _logger.LogError(e.Message);
            }

            return Index();
        }
    }
}
