using CaseAccountingContracts.BindingModels;
using CaseAccountingContracts.ViewModels;
using Microsoft.AspNetCore.Mvc;

namespace CaseAccountingCustomerView.Controllers
{
	public class Contracts : Controller
	{
        public IActionResult Create()
        {
            if (APIUser.User == null)
            {
                return Redirect("~/Home/Enter");
            }
            return View();
        }

        [HttpPost]
        public void Create([FromBody] ContractBindingModel contractModel)
        {
            if (APIUser.User == null)
            {
                throw new Exception("403");
            }
            contractModel.UserId = APIUser.User.Id;
            APIUser.PostRequest("api/contract/create", contractModel);
            Response.Redirect("/Home/Contracts");
        }

        public IActionResult Update(int id)
        {
            if (APIUser.User == null)
            {
                return Redirect("~/Home/Enter");
            }
            ViewBag.Contract = APIUser.GetRequest<ContractViewModel>($"api/contract/get?id={id}");
            return View();
        }

        [HttpPost]
        public void Update([FromBody] ContractBindingModel contractModel)
        {
            if (APIUser.User == null)
            {
                throw new Exception("403");
            }
            contractModel.UserId = APIUser.User.Id;
            APIUser.PostRequest("api/contract/update", contractModel);
            Response.Redirect("/Home/Contracts");
        }

        [HttpPost]
        public void Delete(int id)
        {
            if (APIUser.User == null)
            {
                throw new Exception("403");
            }
            APIUser.PostRequest($"api/contract/delete", new ContractBindingModel() { Id = id });
            Response.Redirect("/Home/Contracts");
        }

        public List<ContractViewModel> GetAllByUser()
        {
            if (APIUser.User == null)
            {
                return new();
            }
            List<ContractViewModel>? contracts = APIUser.GetRequest<List<ContractViewModel>>($"api/contract/getallbyuser?userId={APIUser.User.Id}");
            return contracts ?? new();
        }

        public ContractViewModel? Get(int id)
        {
            if (APIUser.User == null)
            {
                return new();
            }
            ContractViewModel? contract = APIUser.GetRequest<ContractViewModel>($"api/contract/get?id={id}");
            return contract;
        }
    }
}
