using BukiVedi.Shared.Entities;

namespace BukiVedi.Shared.Services
{
    public class AuthProvider
        : IAuthProvider
    {
        private readonly IRepository<Member> _accountRepository;

        public AuthProvider(IRepository<Member> accountRepository)
        {
            _accountRepository = accountRepository;
        }

        public async Task<Member> CreateAccount(Member account)
        {
            if ((await GetAccountByLogin(account.Login)) != null)
            {
                throw new Exception($"Логин '{account.Login}' занят другим аккаунтом");
            }
            return await _accountRepository.Write(account);
        }
        public async Task<Member> GetAccountByLogin(string login) => (await _accountRepository.Get(Filters.Auth.ByLogin(login))).FirstOrDefault()!;
        public async Task<Member> GetAccount(string id) => await _accountRepository.GetById(id);
        public async Task<Member> GetAccount(string login, string password)
        {
            if (string.IsNullOrWhiteSpace(login) || string.IsNullOrWhiteSpace(password))
            {
                return null!;
            }
            var acc = await GetAccountByLogin(login);
            if (acc == null) return null!;

            var hash = Cryptor.HashPassword(password);
            if (string.Equals(hash, acc.PasswordHash, StringComparison.Ordinal))
            {
                return acc;
            }
            return null!;
        }
        public async Task<Member> Update(Member account)
        {
            return await _accountRepository.ReWrite(account);
        }
    }
}
