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

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

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

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

            return View(_ViewPath);
        }

        [HttpPost("Meta")]
        public IActionResult Save(MetaForm request)
        {
            string message;

            if (!ModelState.IsValid)
            {
                message = "메타 태그 설정 값 저장에 실패";
                _logger.LogWarning(message);
                TempData["ErrorMessages"] = message;
                return View(_ViewPath, request);
            }

            Func.SaveConfig(request, _configRepository.Replace);

            message = "메타 태그 설정 값이 정상적으로 저장되었습니다.";
            _logger.LogInformation(message);
            TempData["SuccessMessage"] = message;
            return RedirectToAction("Index");
        }

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