namespace Hims.Api.Validators
{
    using System;
    using System.Threading.Tasks;
    using Domain.Services;
    using IdentityServer4.Models;
    using IdentityServer4.Validation;
    using Shared.Library;

    /// <inheritdoc />
    public class ResourceOwnerPasswordValidator : IResourceOwnerPasswordValidator
    {
        /// <summary>
        /// The account services.
        /// </summary>
        private readonly IAccountService accountServices;

        /// <inheritdoc cref="accountServices" />
        public ResourceOwnerPasswordValidator(IAccountService accountServices) => this.accountServices = accountServices;

        /// <inheritdoc />
        public async Task ValidateAsync(ResourceOwnerPasswordValidationContext context)
        {
            try
            {
                if (context.UserName == context.Password)
                {
                    var accountId = context.UserName.Replace("@@", string.Empty);
                    context.Result = new GrantValidationResult(accountId, "custom");
                }
                else
                {
                    //var values = context.UserName.Split("!!");
                    //context.UserName = values[0];
                    //var accountTypes = values[1];

                    var (accountStatus, accountId) = await this.accountServices.ValidateAsync(context.UserName, context.Password);
                    if (accountStatus != UserAccountStatus.Success)
                    {
                        context.Result = new GrantValidationResult(TokenRequestErrors.InvalidGrant, accountStatus.ToString());
                        return;
                    }

                    context.Result = new GrantValidationResult(accountId.ToString(), "custom");
                }
            }
            catch
            {
                context.Result = new GrantValidationResult(TokenRequestErrors.InvalidRequest, UserAccountStatus.ServerError.ToString());
            }
        }
    }
}