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

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

        public MetaController(ILogger<MetaController> 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("Meta")]
        public IActionResult Index()
        {
            ViewBag.Config = _configRepository.GetAll();

            return View(_ViewPath);
        }

        [HttpPost("Meta")]
        public IActionResult Save(MetaForm 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();
        }
    }
}
