﻿using System.Threading.Tasks;
using System.Web.Http;
using Ebergstedt.OWASP.IndirectReferenceMap.DAL;
using Ebergstedt.OWASP.IndirectReferenceMap.InternalModels;
using Microsoft.AspNet.Identity;

namespace Ebergstedt.OWASP.IndirectReferenceMap.Controllers
{
    public class RegisterUserController : ApiController
    {
        private readonly AuthRepository _authRepository;

        public RegisterUserController()
        {
            _authRepository = new AuthRepository();
        }

        [AllowAnonymous]
        public async Task<IHttpActionResult> Register(UserModel userModel)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            var result = await _authRepository.RegisterUser(userModel);

            var errorResult = GetErrorResult(result);

            if (errorResult != null)
            {
                return errorResult;
            }

            return Ok();
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                _authRepository.Dispose();
            }

            base.Dispose(disposing);
        }

        private IHttpActionResult GetErrorResult(IdentityResult result)
        {
            if (result == null)
            {
                return InternalServerError();
            }

            if (!result.Succeeded)
            {
                if (result.Errors != null)
                {
                    foreach (var error in result.Errors)
                    {
                        ModelState.AddModelError("", error);
                    }
                }

                if (ModelState.IsValid)
                {
                    // No ModelState errors are available to send, so just return an empty BadRequest.
                    return BadRequest();
                }

                return BadRequest(ModelState);
            }

            return null;
        }
    }
}