using Yuna.Website.Server.Infrastructure;
using Yuna.Website.Server.Model;
using Yuna.Website.Server.Storage.Repositories.UserBindings;

namespace Yuna.Website.Server.Services.OpenAuthService
{
    public class OpenAuthService : IOpenAuthService
    {
        private readonly IUserBindingsRepository _userBindingsRepository;
        private readonly ILogger<OpenAuthService> _logger;
        public OpenAuthService(IUserBindingsRepository userBindingsRepository, ILogger<OpenAuthService> logger)
        {
            _userBindingsRepository = userBindingsRepository;
            _logger = logger;
        }

        public UserBinding CreateBinding(User user)
        {
            //Надо переделать, чтобы код и токен точно были уникальные
            var binding = new UserBinding()
            {
                AccessToken = Encrypter.GenerateRandomString(128),
                Code = Encrypter.GenerateRandomString(50),
                UserId = user.Id
            };

            _logger.LogInformation("Created OauthBinding:\n" +
                "UserId: {0}\n" +
                "AccessToken: {1}\n" +
                "Code: {2}\n", user.Id, binding.Code, binding.AccessToken);

            return _userBindingsRepository.Create(binding);
        }

        public bool ValidateLoginRequest(string responseType, string clientId, string host)
        {
            _logger.LogInformation("Host: {0}", host);

            var result = responseType.Equals("code") && clientId.Equals("vasich_yandex_server");

            if (result) _logger.LogInformation("OauthRequest valid");
            else _logger.LogWarning("OauthRequest invalid");

            return result;
        }

        public UserBinding? GetByCode(string code)
        {
            return _userBindingsRepository.GetUserBinding(code);
        }
    }
}
