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

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

        public CompanyController(ILogger<CompanyController> 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("Company")]
        public IActionResult Index()
        {
            var config = _configRepository.GetAll();

            ViewBag.Config = config;
            ViewBag.BankCodes = BankCodeData.List.Select(item => new SelectListItem
            {
                Value = item.Value,
                Text = item.Text,
                Selected = item.Value == config.GetConfig("company_bank_code")
            }).ToList();

            return View(_ViewPath);
        }

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