using CandidateReviewClientApp.Models;
using CandidateReviewContracts.BindingModels;
using CandidateReviewContracts.ViewModels;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using System.Diagnostics;

namespace CandidateReviewClientApp.Controllers
{
    public class CriterionController : Controller
    {
        private readonly ILogger<CriterionController> _logger;

        public CriterionController(ILogger<CriterionController> logger)
        {
            _logger = logger;
        }

        [HttpPost]
        public async Task<IActionResult> AddCriterion(string name)
        {
            string returnUrl = HttpContext.Request.Headers["Referer"].ToString();
            try
            {
                if (string.IsNullOrEmpty(name))
                {
                    throw new Exception("Название критерия не может быть пустым");
                }
                await APIClient.PostRequestAsynchron("api/criterion/create", new CriterionBindingModel
                {
                    Name = name
                });

                return Redirect("/Criterion/ManageCriterions");
            }
            catch (Exception ex)
            {
                return RedirectToAction("Error", new { errorMessage = $"{ex.Message}", returnUrl });
            }
        }

        [HttpGet]
        public async Task<IActionResult> ManageCriterions()
        {
            string returnUrl = HttpContext.Request.Headers["Referer"].ToString();
            try
            {
                var criterions = await APIClient.GetRequestAsync<List<CriterionViewModel>>("api/criterion/list");
                return View(criterions);
            }
            catch (Exception ex)
            {
                return RedirectToAction("Error", new { errorMessage = $"{ex.Message}", returnUrl });
            }
        }

        public IActionResult Delete(int id)
        {
            string returnUrl = HttpContext.Request.Headers["Referer"].ToString();
            try
            {
                APIClient.PostRequest($"api/criterion/delete", new CriterionBindingModel { Id = id });
                return Redirect("~/Criterion/ManageCriterions");
            }
            catch (Exception ex)
            {
                return RedirectToAction("Error", new { errorMessage = $"{ex.Message}", returnUrl });
            }
        }

        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error(string errorMessage, string returnUrl)
        {
            ViewBag.ErrorMessage = errorMessage ?? "Произошла непредвиденная ошибка.";
            ViewBag.ReturnUrl = returnUrl;
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }
    }
}
