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

namespace Back.Controllers
{
    [Route("api/[controller]")]
    [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/{invoiceID}")]
        public async Task<ActionResult<bool>> AddItem([FromRoute] int invoiceID, [FromBody] 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, invoiceID, model, 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, 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.am,
                    fee=model.fee,
                    dis=model.dis,
                    CODID=model.CODID,
                    InvoiceID=invoiceID,
                    
                }));
            }
            else return BadRequest(new List<string> { "خطایی رخ داده" });


        }
        [HttpPut("UpdateItem/{invoiceID}")]
        public async Task<ActionResult<bool>> UpdateItem([FromRoute] int invoiceID, [FromBody] 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, invoiceID, model, eActionValidation.update));
            if (!resultValidationmodel.IsValid)
                return BadRequest(resultValidationmodel.Errors.Select(s => s.ErrorMessage).ToList());

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


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

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

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

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


        }
        [HttpDelete("DeleteItem/{invoiceID}/{invoiceItemID}")]
        public async Task<ActionResult<bool>> DeleteItem([FromRoute] int invoiceID, [FromRoute] 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));

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

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


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

            invoice.LastChangeUserID = Convert.ToInt32(UserID);

      

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

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


        }

    }
}
