using Back.Common;
using Back.Data.Models;
using Back.Services;
using Back.Validations;
using FluentValidation;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Shared.DTOs;
using System.Net;
using System.Runtime.ConstrainedExecution;

namespace Back.Controllers
{
    [Route("api/[controller]")]
    [Authorize]
    [ApiController]
    public class InvoiceItemController : ControllerBase
    {
        private readonly servInvoiceItem _servInvoiceItem;
        private readonly servUser _servUser;
        private readonly AUInvoiceItemValidation _validationInvoiceItem;
        private readonly servInvoice _servInvoice;
        public InvoiceItemController(servInvoiceItem servInvoiceItem, AUInvoiceItemValidation validationInvoiceItem
            , servUser servUser, servInvoice servInvoice)
        {
            _servInvoiceItem = servInvoiceItem;
            _validationInvoiceItem = validationInvoiceItem;
            _servUser = servUser;
            _servInvoice = servInvoice;

        }
        [HttpPost("AddItem")]
        public async Task<ActionResult<bool>> AddItem([FromBody]InvoiceItemAction<InvoiceItemDTO> model)
        {
            //-----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 _validationInvoiceItem.ValidateAsync(Tuple.Create(user.RolUsers.First().CompanyID, model.invoiceID, model.item, eActionValidation.add));
            if (!resultValidationmodel.IsValid)
                return BadRequest(resultValidationmodel.Errors.Select(s => s.ErrorMessage).ToList());

            //-----Get invoice
            Invoice invoice = await _servInvoice.GetInvoiceByInvoiceID(user.RolUsers.First().CompanyID, model.invoiceID);
            if (invoice == null)
                return BadRequest(new List<string> { "invoice notFound..." });


            invoice.LastChangeUserID = Convert.ToInt32(UserID);

            if (await _servInvoice.UpdateInvoice(invoice))
            {
                return Ok(await _servInvoiceItem.Add(new InvoiceItem
                {
                    am=model.item.am,
                    fee=model.item.fee,
                    dis=model.item.dis,
                    CODID=model.item.CODID,
                    InvoiceID=model.invoiceID,
                    
                }));
            }
            else return BadRequest(new List<string> { "خطایی رخ داده" });


        }
        [HttpPut("UpdateItem")]
        public async Task<ActionResult<bool>> UpdateItem([FromBody] InvoiceItemAction<InvoiceItemDTO> model)
        {
            //-----GetUserAndCompany
            var claim = HttpContext.User.Claims.First(c => c.Type == "UserID");
            var UserID = claim.Value;
            var user = await _servUser.GetUserByUserID(Convert.ToInt32(UserID));


            //-----Get invoice
            Invoice invoice = await _servInvoice.GetInvoiceByInvoiceID(user.RolUsers.First().CompanyID, model.invoiceID);
            if (invoice == null)
                return BadRequest(new List<string> { "invoice notFound..." });



            //-----Validaton
            var resultValidationmodel = await _validationInvoiceItem.ValidateAsync(Tuple.Create(user.RolUsers.First().CompanyID, model.invoiceID, model.item, eActionValidation.update));
            if (!resultValidationmodel.IsValid)
            {
                if (invoice.invoiceType != InvoiceType.BackFrmSale || (invoice.invoiceType != InvoiceType.BackFrmSale
                    && resultValidationmodel.Errors.Count > 1))
                {
                    return BadRequest(resultValidationmodel.Errors.Select(s => s.ErrorMessage).ToList());
                }
             
            }

           
           


          var invoiceitem=await  _servInvoiceItem.Getinvoiceitem(user.RolUsers.First().CompanyID, model.invoiceID, model.item.ID.Value);
            if (invoiceitem == null)
                return BadRequest(new List<string> { "invoice Item notFound..." });

            if (invoice.invoiceType==InvoiceType.BackFrmSale && invoiceitem.am < model.item.am)
                return BadRequest(new List<string> { "در حالت برگشت از فروش تعداد آیتم فقط میتواند کاهشی باشد" });
            
            invoice.LastChangeUserID = Convert.ToInt32(UserID);

            if (invoice.invoiceType == InvoiceType.BackFrmSale)
            invoiceitem.am = model.item.am;
            else
            {
                invoiceitem.am = model.item.am;
                invoiceitem.fee = model.item.fee;
                invoiceitem.dis = model.item.dis;
                invoiceitem.CODID = model.item.CODID;
            }

            if (await _servInvoice.UpdateInvoice(invoice))
                return Ok(await _servInvoiceItem.Update(invoiceitem));
            
            else return BadRequest(new List<string> { "خطایی رخ داده" });


        }
        [HttpDelete("DeleteItem/{InvoiceItemID}")]
        public async Task<ActionResult<bool>> DeleteItem(int InvoiceItemID)
        {

            //-----GetUserAndCompany
            var claim = HttpContext.User.Claims.First(c => c.Type == "UserID");
            var UserID = claim.Value;
            var user = await _servUser.GetUserByUserID(Convert.ToInt32(UserID));

            //-----Get invoice
            var invoiceitem = await _servInvoiceItem.GetInvoiceItemByInvoiceItemID(user.RolUsers.First().CompanyID, InvoiceItemID);
            if (invoiceitem == null)
                return NotFound(new List<string> { "invoice Item notFound..." });

            //-----Validaton
            var resultValidationmodel = await _validationInvoiceItem.ValidateAsync(Tuple.Create(user.RolUsers.First().CompanyID, invoiceitem.InvoiceID.Value, new InvoiceItemDTO(), eActionValidation.delete)) ;
            if (!resultValidationmodel.IsValid)
                return BadRequest(resultValidationmodel.Errors.Select(s => s.ErrorMessage).ToList());



            invoiceitem.invoice.LastChangeUserID = Convert.ToInt32(UserID);

      

            if (await _servInvoice.UpdateInvoice(invoiceitem.invoice))
                return Ok(await _servInvoiceItem.Delete(invoiceitem));

            else return BadRequest(new List<string> { "خطایی رخ داده" });


        }
      

    }
}
