using Back.Services;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Shared.DTOs.Serch;
using Shared.DTOs;
using System.Xml.Linq;
using Back.Common;
using Back.Validations;
using Microsoft.AspNetCore.Authorization;

namespace Back.Controllers
{
    [Route("api/[controller]")]
    [Authorize]
    [ApiController]
    public class CODController : ControllerBase
    {
        private readonly ServCOD _servCOD;
        private readonly servUser _servUser;
        private readonly AddOrCodValidation _addorupdateCodValidation;
        public CODController(ServCOD servCOD, servUser servUser, AddOrCodValidation addorupdateCodValidation)
        {
            _servCOD = servCOD;
            _servUser = servUser; 
            _addorupdateCodValidation = addorupdateCodValidation;
        }
        [HttpPost("GetAll")]
        public async Task<ActionResult<PagingDto<RCOD>?>> GetAll([FromBody] ItemSerchGetCOD itemSerch)
        {
            var claim = HttpContext.User.Claims.First(c => c.Type == "UserID");
            var UserID = claim.Value;
            var user = await _servUser.GetUserByUserID(Convert.ToInt32(UserID));
           // if (!await _checkPermission.AllowSYSGetCOD(Convert.ToInt32(UserID), user.RolUsers.First().CompanyID)) return Forbid("شما دسترسی به خواندن اطلاعات کالا را نداربد");
            return Ok(await _servCOD.GetCODs(user.RolUsers.First().CompanyID, itemSerch));
        }
        [HttpGet("GetCod/{ID}")]
        public async Task<ActionResult<RCOD>> GetCod(int ID)
        {
            var claim = HttpContext.User.Claims.First(c => c.Type == "UserID");
            var UserID = claim.Value;
            var user = await _servUser.GetUserByUserID(Convert.ToInt32(UserID));
            var cod = await _servCOD.GetCodByCodID(ID, user.RolUsers.First().CompanyID);
            return Ok(new RCOD
            {
                ID = cod.ID,
                TaxID = cod.ItemTaxID,
                Title = cod.Title,
                Unit = cod.CODUnit.Title,
                UnitID = cod.UnitID,
                TaxRate = cod.TaxRate


            });
        }
        [HttpGet("GetAllForidName")]
        public async Task<ActionResult<List<CODIdName<int>>>> GetAllForidName()
        {
            var claim = HttpContext.User.Claims.First(c => c.Type == "UserID");
            var UserID = claim.Value;
            var user = await _servUser.GetUserByUserID(Convert.ToInt32(UserID));



            return Ok(await _servCOD.GetCODs(user.RolUsers.First().CompanyID));


        }
        [HttpGet("GetUnits")]
        [AllowAnonymous]
        public async Task<ActionResult<List<IdName<int>>>> GetUnits()
        {
            return Ok(await _servCOD.GetUnits());
        }
        [HttpPost("Add")]
        public async Task<ActionResult<bool>> Add(RCOD item)
        {
          
            var claim = HttpContext.User.Claims.First(c => c.Type == "UserID");
            var UserID = claim.Value;
            var user = await _servUser.GetUserByUserID(Convert.ToInt32(UserID));

            var resultValidationmodel = await _addorupdateCodValidation.ValidateAsync(Tuple.Create(user.RolUsers.First().CompanyID, item, eActionValidation.add));
            if (!resultValidationmodel.IsValid)
                return BadRequest(resultValidationmodel.Errors.Select(s => s.ErrorMessage).ToList());

            return Ok(await _servCOD.AddOrUpdateCod(new Data.Models.CODItem
            {
                
                CompanyID = user.RolUsers.First().CompanyID,
                TaxRate = item.TaxRate,
                Title = item.Title,
                UnitID=item.UnitID,
                ItemTaxID=item.TaxID,   
                IsDeleted = false
            }));
        }
        [HttpPut("Update")]
        public async Task<ActionResult<bool>> Update(RCOD item)
        {
            //-----GetUserAndCompany
            var claim = HttpContext.User.Claims.First(c => c.Type == "UserID");
            var UserID = claim.Value;
            var user = await _servUser.GetUserByUserID(Convert.ToInt32(UserID));

            //-----Validaton
            var resultValidationmodel = await _addorupdateCodValidation.ValidateAsync(Tuple.Create(user.RolUsers.First().CompanyID, item, eActionValidation.update));
            if (!resultValidationmodel.IsValid)
                return BadRequest(resultValidationmodel.Errors.Select(s => s.ErrorMessage).ToList());

            //-----Get Cod
            var Cod = await _servCOD.GetCodByCodID(item.ID.Value, user.RolUsers.First().CompanyID);
            if (Cod == null)
                return BadRequest(new List<string> { "Cod notFound..." });

            ////-----change Cod
            Cod.TaxRate = item.TaxRate;
            Cod.Title = item.Title;
            Cod.UnitID = item.UnitID;
            Cod.ItemTaxID = item.TaxID;
            Cod.IsDeleted = false;

            //----Update and sendResult
            return Ok(await _servCOD.AddOrUpdateCod(Cod));
        }
        [HttpDelete("Delete/{ID}")]
        public async Task<ActionResult<bool>> Delete(int ID)
        {
            //-----GetUserAndCompany
            var claim = HttpContext.User.Claims.First(c => c.Type == "UserID");
            var UserID = claim.Value;
            var user = await _servUser.GetUserByUserID(Convert.ToInt32(UserID));

            //-----Get Cus
            var cod = await _servCOD.GetCodByCodID(ID, user.RolUsers.First().CompanyID);
            if (cod == null)
                return NotFound();

            //----Update and sendResult
            return Ok(await _servCOD.DeleteCod(cod));
        }
    }
}
