using Domain.Identity;
using Infrastructure;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;
using Models.Identity;
using Services.Identity;
using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Hosting;

namespace Api.Controllers
{
    [ApiController]
    [EnableCors("AllowAll")]

    public class AuthController : BaseController
    {
        private readonly IAuthService authService;
        private readonly IWebHostEnvironment _hostingEnvironment;

        public AuthController(IServiceProvider serviceProvider) : base(serviceProvider)
        {
            authService=serviceProvider.GetService<IAuthService>();
        }



        [HttpPost]
        [ProducesResponseType(typeof(OtpRequestResult), StatusCodes.Status200OK)]
        public async Task<IActionResult> SignUp([FromBody] SignUpModel model)
        {
            var existed = authService.GetByUsername(model.Email) != null;
            if (existed)
            {
                return BadRequest("Email is already registered!");
            }
            var account = new Account
            {
                Email = model.Email,
                Username = model.Email,
                Password = model.Password,
                Name = model.Name
            };
            authService.Add(account);
            var token = await authService.GenerateLoginToken(account);
            return Ok(new OtpRequestResult());
        }



        [HttpPost]
        [ProducesResponseType(typeof(PlainToken), StatusCodes.Status200OK)]
        [ProducesResponseType(StatusCodes.Status401Unauthorized)]
        public async Task<IActionResult> Login([FromBody] LoginModel model)
        {
            var account = await authService.GetByUsernameAndPassword(model.Username, model.Password);
            if (account == null) return Unauthorized();

            var loginToken = await authService.GenerateLoginToken(account);
            var plainToken = await authService.GeneratePlainToken(account, loginToken.Token);
            if (plainToken == null) return Unauthorized();

            return Ok(plainToken);
        }

        [HttpGet]
        [ProducesResponseType(typeof(CheckLoginResponse), statusCode: StatusCodes.Status200OK)]
        [ProducesResponseType(StatusCodes.Status401Unauthorized)]
        public IActionResult Check()
        {
            var u = User;
            try
            {

                var res = Mapper.Map<CheckLoginResponse>(CurrentAccount);
                try
                {
                    res.IsDeveloper = User.IsInRole(Consts.Developer);
                }
                catch
                {
                }
                return Ok(res);
            }
            catch (Exception)
            {
                return Unauthorized();
            }
        }



    }
}
