using Insight.Api.Models;
using Insight.Infrastructure.Models;
using Insight.Infrastructure.Services;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

namespace Insight.Api.Controllers
{
    [ApiController, Route("api/accounts")]
    public class AccountController : ControllerBase
    {
        private readonly IdentityService _identityService;
        private readonly AccountService _accountService;
        private readonly ILogger<AccountController> _logger;

        public AccountController(IdentityService identityService, AccountService accountService, ILogger<AccountController> logger)
        {
            _identityService = identityService;
            _accountService = accountService;
            _logger = logger;
        }

        [HttpGet, Authorize]
        public async Task<IActionResult> Get([FromQuery] PagedDataRequest request, CancellationToken cancellationToken)
        {
            try
            {
                var result = await _accountService.GetAsync(
                offset: request.Offset,
                limit: request.Limit,
                request: Request,
                response: Response,
                cancellationToken: cancellationToken).ConfigureAwait(false);

                return Ok(result);
            }
            catch (UnauthorizedAccessException ex)
            {
                return Unauthorized(ex.ToString());
            }
            catch (Exception ex)
            {
                return BadRequest(ex.Message);
            }
        }

        [HttpPost("register"), Authorize]
        public async Task<ActionResult> Register([FromBody] RegistrationModel model)
        {
            if (string.IsNullOrWhiteSpace(model.Email)) return BadRequest("Email Required");
            if (string.IsNullOrWhiteSpace(model.Password)) return BadRequest("Password Required");
            if (string.IsNullOrWhiteSpace(model.ConfirmPassword)) return BadRequest("Password Confirmation Required");

            if (model.Password != model.ConfirmPassword) return BadRequest("Passwords do not match");

            try
            {
                var result = await _identityService.CreateUserAsync(model.Email, model.Password).ConfigureAwait(false);

                if (result.Succeeded is false) return BadRequest(result.Errors);
            }
            catch (UnauthorizedAccessException ex)
            {
                return Unauthorized(ex.Message);
            }
            catch (Exception ex)
            {
                return BadRequest(ex.Message);
            }

            //await _userManager.AddToRoleAsync(user, "Visitor");

            return Ok(model.Email);
        }
    }
}