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

namespace Back.Controllers
{
    [Route("api/[controller]")]
    [Authorize]
    [ApiController]
    public class UserController : ControllerBase
    {
        private readonly servUser _servUser;
        private readonly servCompany _servCompany;
        private readonly MobileValidation _mobilevalidation;
        private readonly ServValidatinMsg _servValidatinMsg;
        private readonly servSendMsg _servSendMsg;
        private readonly servNotification _servNotification;
        public UserController(servUser servUser, MobileValidation mobilevalidation, servCompany servCompany
            , ServValidatinMsg servValidatinMsg, servSendMsg servSendMsg, servNotification servNotification)
        {

            _servUser = servUser;
            _mobilevalidation = mobilevalidation;
            _servCompany = servCompany;
            _servValidatinMsg = servValidatinMsg;
            _servSendMsg = servSendMsg;
            _servNotification = servNotification;
        }
        [HttpPost("authenticate")]
        [AllowAnonymous]
        public async Task<ActionResult<UserAuthenticationDTO>> Login([FromBody]Authentication model)
        {
            var result = await _servUser.UserAuthentication(model.Username, model.Password);
            if (result != null) return Ok(result);
            else return NotFound("کاربری با این مشخصات یافت نشد");
        }
        [HttpGet("CheckAuthenticate")]
        public async Task<ActionResult<UserAuthenticationDTO>> CheckAuthenticate()
        {
          //  var accessToken = Request.Headers["Authorization"].ToString().Split(' ')[1];

            var claim = HttpContext.User.Claims.First(c => c.Type == "UserID");
            var UserID = claim.Value;
            var result = await _servUser.UserAuthentication(UserID,newtoken:false);
            return Ok(result);

        }
        [HttpPost("ChangePassword")]
        public async Task<ActionResult<bool>> ChangePassword(ChangePasswordDto item)
        {
            if (item.newPass.Trim() != item.renewPass.Trim())
                return BadRequest(new List<string> { "تکرار کلمه عبور با کلمه عبور مطابقت ندارد" });
            if (item.newPass.Trim().Length <= 3)
                return BadRequest(new List<string> { "کلمه عبور جدید باید بیشتر از 3کاراکتر باشد" });
            var UserID = HttpContext.User.Claims.First(c => c.Type == "UserID").Value;
            if (!await _servUser.PermissionChangePassword(item.oldPass.Trim(), Convert.ToInt32(UserID)))
                return BadRequest(new List<string> { "کلمه عبور قبلی صحیح نمی باشد" });
            return Ok(await _servUser.ChangePassword(item.newPass.Trim(), Convert.ToInt32(UserID)));

        }
        [HttpGet("ChangeUserName/{newUsername}")]
        public async Task<ActionResult<bool>> ChangeUserName(string newUsername)
        {
            var resultValidationmodel = await _mobilevalidation.ValidateAsync(Tuple.Create(newUsername, ActionMobileValidation.nonExistMobile));
            if (!resultValidationmodel.IsValid)
                return BadRequest(resultValidationmodel.Errors.Select(s => s.ErrorMessage).ToList());

            var UserID = HttpContext.User.Claims.First(c => c.Type == "UserID").Value;

            var modelvc = await _servValidatinMsg.GenerateCode(new VerificationCode
            {
                prm = UserID,
                val = newUsername,
                Type = "ChangeUserName"
            });

            _servSendMsg.toContinue(modelvc.Code.ToString(),newUsername, "تغییر نام کاربری");
            return Ok(modelvc.ID);

          //  return Ok(await _servUser.ChangeUserName(newUsername, Convert.ToInt32(UserID)));
        }

        [HttpGet("GetDashBoard")]
        public async Task<ActionResult<DashBoardDTO>> GetDashBoard()
        {
            var claim = HttpContext.User.Claims.First(c => c.Type == "UserID");
            var UserID = claim.Value;
          

            return Ok(await _servUser.GetDashBoard(Convert.ToInt32(UserID)));

        }
        [HttpPut("ReadNotification/{ntID}")]
        public async Task<ActionResult<bool>> ReadNotification(int ntID)
        {
            var claim = HttpContext.User.Claims.First(c => c.Type == "UserID");
            var UserID = claim.Value;
            return Ok(await _servNotification.ReadNotification(Convert.ToInt32(UserID), ntID));

           
        }

    }
}
