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

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

        public RegisterController(ILogger<RegisterController> logger, IConfigRepository configRepository, ISetupService setupService)
        {
            _logger = logger;
            _configRepository = configRepository;
            _setupService = setupService;
        }

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

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

            return View(_ViewPath);
        }

        [HttpPost("Register")]
        public IActionResult Save(RegisterForm request)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    throw new Exception("회원가입 설정 값 저장에 실패");
                }

                Functions.SaveConfig(request, _configRepository.Replace);
                _setupService.RefreshConfigAsync().Wait();

                string message = "회원가입 설정 값이 정상적으로 저장되었습니다.";
                TempData["SuccessMessage"] = message;
                _logger.LogInformation(message);
            }
            catch (Exception e)
            {
                TempData["ErrorMessages"] = e.Message;
                _logger.LogError(e, e.Message);
            }

            return Index();
        }
    }
}
