using Back.Common;
using Back.Data.Models;
using Back.Services;
using Back.Validations;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Service;
using Shared.DTOs;
using System.Net;
using System.Reflection.Emit;

namespace Back.Controllers
{
    [Route("api/[controller]")]
    [Authorize]
    [ApiController]
    public class CustomerController : ControllerBase
    {
        private readonly servUser _servUser;
        private readonly servCustomer _servCus;
        private readonly AddOrCustomerValidation _addorupdateCustomerValidation;
        public CustomerController( servUser servUser, servCustomer servCus, AddOrCustomerValidation addorupdateCustomerValidation)
        {
            _addorupdateCustomerValidation = addorupdateCustomerValidation;
            _servUser = servUser;
            _servCus = servCus;
        }
        [HttpPost("GetAll")]
        public async Task<ActionResult<PagingDto<RCustomer>>> GetAll(ItemSerchGetCustomer 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.AllowSYSGetCustomer(Convert.ToInt32(UserID), user.RolUsers.First().CompanyID)) return Forbid("شما دسترسی به خواندن اطلاعات مشتری را نداربد");

            return Ok(await _servCus.GetCustomers(user.RolUsers.First().CompanyID, itemSerch));


        }
        [HttpGet("GetCustomer/{ID}")]
        public async Task<ActionResult<RCustomer>> GetCustomer(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 cus = await _servCus.GetCustomerByCustomerID(ID, user.RolUsers.First().CompanyID);
            return Ok(new RCustomer
            {
                Address = cus.Address,
                BranchID = cus.BranchID,
                CustomerType = cus.CustomerType,
                CustomerTypeTitle = cus.CustomerType.GetEnumDisplayName(),
                EconomicCode = cus.EconomicCode,
                Email = cus.Email,
                FullName = cus.FullName,
                ID = ID,
                Info = cus.Info,
                MeliCode = cus.MeliCode,
                PassportNumber = cus.PassportNumber,
                Phone = cus.Phone,
                ZipCode = cus.ZipCode
                

            });
        }
        [HttpGet("GetAllForidName")]
        public async Task<ActionResult<List<ForCustomerSearch>>> GetAllForSearch()
        {
            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 _servCus.GetCustomers(user.RolUsers.First().CompanyID));


        }
        [HttpPost("Add")]
        public async Task<ActionResult<bool>> Add(RCustomer 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 _addorupdateCustomerValidation.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 _servCus.AddOrUpdateCustomer(new Data.Models.Customer
            {
                Address = item.Address,
                BranchID = item.BranchID,
                CompanyID = user.RolUsers.First().CompanyID,
                CustomerType = item.CustomerType,
                EconomicCode = item.EconomicCode,
                Email = item.Email,
                FullName = item.FullName,
                Info = item.Info,
                MeliCode = item.MeliCode,
                PassportNumber = item.PassportNumber,
                Phone = item.Phone,
                ZipCode = item.ZipCode,
                IsDeleted = false
            }));
        }
        [HttpPut("Update")]
        public async Task<ActionResult<bool>> Update(RCustomer 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 _addorupdateCustomerValidation.ValidateAsync(Tuple.Create(user.RolUsers.First().CompanyID, item, eActionValidation.update));
            if (!resultValidationmodel.IsValid)
                return BadRequest(resultValidationmodel.Errors.Select(s => s.ErrorMessage).ToList());
            
            //-----Get Cus
            var cus = await _servCus.GetCustomerByCustomerID(item.ID.Value, user.RolUsers.First().CompanyID);
            if (cus == null)
                return BadRequest(new List<string> { "Cus notFound..." });

            //-----change Cus
            cus.Address = item.Address;
            cus.BranchID = item.BranchID;
            cus.CompanyID = user.RolUsers.First().CompanyID;
            cus.CustomerType = item.CustomerType;
            cus.EconomicCode = item.EconomicCode;
            cus.Email = item.Email;
            cus.FullName = item.FullName;
            cus.Info = item.Info;
            cus.MeliCode = item.MeliCode;
            cus.PassportNumber = item.PassportNumber;
            cus.Phone = item.Phone;
            cus.ZipCode = item.ZipCode;
            cus.IsDeleted = false;

            //----Update and sendResult
            return Ok(await _servCus.AddOrUpdateCustomer(cus));
        }
        [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 cus = await _servCus.GetCustomerByCustomerID(ID, user.RolUsers.First().CompanyID);
            if (cus == null)
                return NotFound();

            //----Update and sendResult
            return Ok(await _servCus.DeleteCustomer(cus));
        }
    }
}
