using Back.Data.Models;
using Back.Services;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.HttpResults;
using Microsoft.AspNetCore.Mvc;
using Shared.DTOs;

namespace Back.Controllers
{
    [Route("api/[controller]")]
    [Authorize]
    [ApiController]
    public class CompanyController : ControllerBase
    {
        private readonly servCompany _servCompany;
        private readonly servUser _servUser;
        private readonly servTaxPayer _servTaxPayer;
        public CompanyController(servCompany servCompany, servUser servUser, servTaxPayer servTaxPayer)
        {
            _servUser = servUser;
            _servCompany = servCompany;
            _servTaxPayer = servTaxPayer;
        }
        [HttpGet("GetCompany")]
        public async Task<ActionResult<CompanyDTO>> GetCompany()
        {
            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 _servCompany.GetCompany(user.RolUsers.First().CompanyID));
        }
        [HttpPost("ChangeLogo")]
        public async Task<ActionResult<bool>> ChangeLogo(byte[] logo)
        {
            if (logo == null)
                return BadRequest();
           
                var claim = HttpContext.User.Claims.First(c => c.Type == "UserID");
            var UserID = claim.Value;
            var result = await _servUser.GetUserByUserID(Convert.ToInt32(UserID));
            var company = result?.RolUsers.First().Company;
            company.Logo= logo;
            return Ok(await _servCompany.AddORUpdateCompanyBoolResult(company));
        }
        [HttpGet("ChangeName/{name}")]
        public async Task<ActionResult<bool>> ChangeName(string name)
        {
            if (string.IsNullOrEmpty(name) || name.Length<=3)
                return BadRequest(new List<string> { "نام صحیح نمی باشد"});
            var claim = HttpContext.User.Claims.First(c => c.Type == "UserID");
            var UserID = claim.Value;
            var user = await _servUser.GetUserByUserID(Convert.ToInt32(UserID));
            var company = user?.RolUsers.First().Company;
            company.Name = name;
            user.Fullname=name;
            await _servUser.UpdateUser(user);
            return Ok(await _servCompany.AddORUpdateCompanyBoolResult(company));
        }
        [HttpGet("TaxPayerInfo")]
        public async Task<ActionResult<TaxPayerInfoDto>> TaxPayerInfo()
        {
            var claim = HttpContext.User.Claims.First(c => c.Type == "UserID");
            var UserID = claim.Value;
            var user = await _servUser.GetUserByUserID(Convert.ToInt32(UserID));
            var company = user?.RolUsers.First().Company;
            return Ok(new TaxPayerInfoDto
            {
                EconomicCode = company.EconomicCode,
                PrivateKey = company.PrivateKey ,
                UniqeMemory = company.UniqeMemory ,
                BranchID=company.BranchID,
            });
        }
        [HttpPut("ChangeTaxPayerInfo")]
        public async Task<ActionResult<bool>> ChangeTaxPayerInfo(TaxPayerInfoDto model)
        {
            var claim = HttpContext.User.Claims.First(c => c.Type == "UserID");
            var UserID = claim.Value;
            var user = await _servUser.GetUserByUserID(Convert.ToInt32(UserID));

            if (!string.IsNullOrEmpty(model.BranchID) && (model.BranchID.Length > 10 || !int.TryParse(model.BranchID, out int a)))
                return BadRequest(new List<string> {"مقدار کد شعبه صحیح نمی باشد" });

            if (!string.IsNullOrEmpty(model.UniqeMemory) && (model.UniqeMemory.Length !=6 ))
                return BadRequest(new List<string> { "مقدار حافظه مالیاتی صحیح نمی باشد" });

            var company = user?.RolUsers.First().Company;
            if (await _servTaxPayer.ExistSuccessfulorSendorpendingInvoiceinCompanyID(company.ID) &&
                (model.EconomicCode != company.EconomicCode || model.PrivateKey != company.PrivateKey || model.UniqeMemory != company.UniqeMemory))
                return BadRequest(new List<string> { "به دلیل اینکه صورتحسابی با مشخصات کلیدی شما به سازمان مالیات ارسال شده امکان تغییر این موارد را ندارید" +
                    '\n' + "فیلدهای کلیدی شامل (کداقتصادی،شناسه حافظه مالیاتی،کلید خصوصی)" });

            if (await _servTaxPayer.CheckingTheCompanyKeyInformation(company.ID, model.UniqeMemory, model.PrivateKey, model.EconomicCode))
                return BadRequest(new List<string> { "فیلدهای کلیدی شامل (کداقتصادی،شناسه حافظه مالیاتی،کلید خصوصی)" + " برای شرکت دیگری ثبت شده است" });

           
            company.EconomicCode = model.EconomicCode;
            company.PrivateKey = model.PrivateKey;  
            company.UniqeMemory = model.UniqeMemory;
            company.BranchID = model.BranchID;
            return Ok(await _servCompany.AddORUpdateCompanyBoolResult(company));
        }
    }
}
