using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using TeamManiacs.Core.Models;
using TeamManiacs.Data;

namespace ASP.Back.Libraries
{
    public class PasswordManagement
    {
       private Crypto crypto;

        public PasswordManagement(IWebHostEnvironment hostEnvironment) {

            crypto = new Crypto(hostEnvironment, Crypto.ObjectType.Password);

        }
        public bool ValidatePassword(string receivedPassword, Byte[] storedPassword)
        {
           
            if(string.IsNullOrEmpty(receivedPassword) || storedPassword == null)
            {
                return false;
            }
            return crypto.DecryptToString(storedPassword) == receivedPassword;
        }
        public byte[] EncryptPassword(string receivedPassword)
        {
            return crypto.EncryptToBytes(receivedPassword);
        }
        public string DecryptPassword(Byte[] storedPassword)
        {
            return crypto.DecryptToString(storedPassword);
        }


        public Users? Authenticate(TeamManiacsDbContext context, Login login)
        {
            byte[] encryptedPassword = EncryptPassword(login.Password);
            if (encryptedPassword == null)
            {
                return null;
            }
            string username = login.Username?.ToLower();
            string email = login.Email?.ToLower();
            var currentUser = context.UserModels.
                                FirstOrDefault(x =>
                                (x.Username.ToLower() == username || x.Email.ToLower() == email || x.UserId == login.UserId)
                             && x.Password == encryptedPassword);
            return currentUser;

        }

    }
}
