using System.Diagnostics;
using bitforum.Models;
using bitforum.Models.Page;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;

namespace bitforum.Controllers.Page
{
    [Authorize]
    [Route("Page")]
    public class DocumentController : Controller
    {
        private readonly ILogger<DocumentController> _logger;
        private readonly DefaultDbContext _db;
        private readonly IConfiguration _config;
        private readonly string _IndexViewPath = "~/Views/Page/Document/Index.cshtml";
        private readonly string _WriteViewPath = "~/Views/Page/Document/Write.cshtml";
        private readonly string _EditViewPath = "~/Views/Page/Document/Edit.cshtml";

        public DocumentController(ILogger<DocumentController> logger, DefaultDbContext db, IConfiguration config)
        {
            _logger = logger;
            _db = db;
            _config = config;
        }

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

        [HttpGet("Document")]
        public IActionResult Index()
        {
            ViewBag.siteURL = _config["AppConfig:AppName"];
            ViewBag.Documents = _db.Document.OrderByDescending(c => c.ID).ToList();

            return View(_IndexViewPath);
        }

        [HttpGet("Document/Write")]
        public IActionResult Write()
        {
            ViewBag.siteURL = _config["AppConfig:AppName"];
            return View(_WriteViewPath);
        }

        [HttpPost("Document/Create")]
        public async Task<IActionResult> Create(Document request)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    throw new Exception("유효성 검사에 실패하였습니다.");
                }

                // 중복확인
                if (await _db.Document.AnyAsync(c => c.Code == request.Code))
                {
                    throw new Exception("이미 존재하는 Code 주소입니다.");
                }


                request.UpdatedAt = null;
                request.CreatedAt = DateTime.Now;

                _db.Document.Add(request);
                int affectedRows = await _db.SaveChangesAsync();

                if (affectedRows <= 0)
                {
                    throw new Exception("문서 등록 중 오류가 발생했습니다.");
                }

                string message = "문서가 정상적으로 등록되었습니다.";
                TempData["SuccessMessage"] = message;
                _logger.LogInformation(message);
                return RedirectToAction("Index");
            }
            catch (Exception e)
            {
                _logger.LogError(e, e.Message);
                TempData["ErrorMessages"] = e.Message;
                return View(_WriteViewPath, request);
            }
        }

        [HttpGet("Document/Edit/{id}")]
        public async Task<IActionResult> Edit(int id)
        {
            ViewBag.siteURL = _config["AppConfig:AppName"];

            try
            {
                if (id <= 0)
                {
                    throw new Exception("유효하지 않은 문서 ID입니다.");
                }

                var document = await _db.Document.FirstAsync(c => c.ID == id);

                if (document is null)
                {
                    throw new Exception("사용자 정보를 찾을 수 없습니다.");
                }

                return View(_EditViewPath, document);
            }
            catch (Exception e)
            {
                _logger.LogError(e, e.Message);
                TempData["ErrorMessages"] = e.Message;
                return Index();
            }
        }

        [HttpPost("Document/Update")]
        public async Task<IActionResult> Update(Document request)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    throw new Exception("유효성 검사에 실패하였습니다.");
                }

                // 중복확인
                if (await _db.Document.AnyAsync(c => c.Code == request.Code && c.ID != request.ID))
                {
                    throw new Exception("이미 존재하는 Code 주소입니다.");
                }

                // 기존 문서 조회
                var document = await _db.Document.FindAsync(request.ID);

                if (document is null)
                {
                    throw new Exception("사용자 정보를 찾을 수 없습니다.");
                }

                document.IsActive = request.IsActive;
                document.Code = request.Code;
                document.Subject = request.Subject;
                document.Content = request.Content;
                document.UpdatedAt = DateTime.Now;

                _db.Document.Update(document);

                int affectedRows = await _db.SaveChangesAsync();
                if (affectedRows <= 0)
                {
                    throw new Exception("문서 수정 중 오류가 발생했습니다.");
                }

                string message = "문서가 정상적으로 수정되었습니다.";
                TempData["SuccessMessage"] = message;
                _logger.LogInformation(message);
                return RedirectToAction("Edit", new { request.ID });
            }
            catch (Exception e)
            {
                _logger.LogError(e, e.Message);
                TempData["ErrorMessages"] = e.Message;
                return View(_EditViewPath, request);
            }
        }

        [HttpGet("Document/Delete/{id}")]
        public async Task<IActionResult> Delete(int id)
        {
            try
            {
                if (id <= 0)
                {
                    throw new Exception("유효하지 않은 문서 ID입니다.");
                }

                var document = await _db.Document.FindAsync(id);
                if (document == null)
                {
                    throw new Exception("문서 정보를 찾을 수 없습니다.");
                }

                _db.Document.Remove(document);

                int affectedRows = await _db.SaveChangesAsync();
                if (affectedRows <= 0)
                {
                    throw new Exception("문서 삭제 중 오류가 발생했습니다.");
                }

                string message = "문서가 정상적으로 삭제되었습니다.";
                TempData["SuccessMessage"] = message;
                _logger.LogInformation(message);
                return RedirectToAction("Index");
            }
            catch (Exception e)
            {
                _logger.LogError(e, e.Message);
                TempData["ErrorMessages"] = e.Message;
                return Index();
            }
        }
    }
}
