using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using adas_core.Domain.Models.GroupedObservations;
using MongoDB.Bson;

namespace adas_core.Domain.Utils;

public static class CryptoAdas
{
    private static readonly Regex PassRegex = new("^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#?!@$%^&*-]).{8,}$");

    public static string CreateMd5(string input)
    {
        using var md5 = MD5.Create();
        var inputBytes = Encoding.ASCII.GetBytes(input);
        var hashBytes = md5.ComputeHash(inputBytes);

        var sb = new StringBuilder();
        for (var i = hashBytes.Length - 1; i >= 0; i--) sb.Append(hashBytes[i].ToString("X2"));

        var res = sb.ToString();
        return res;
    }

    public static string CreateMd5GroupedObs(GroupedField gF, ObjectId patientId)
    {
        var names = CollectionsUtils.IfEmptyOrNull(gF.Names, [gF.Name ?? string.Empty]);

        return CreateMd5(patientId +
                         string.Join("+", names.Select(c => c.ToString())) +
                         gF.Max +
                         gF.Since +
                         gF.Regularity +
                         string.Join("+", gF.Result.Select(c => c.ToString())));
    }

    public static string CreateBCrypt(string input)
    {
        return BCrypt.Net.BCrypt.HashPassword(input);
    }

    public static bool VerifyPassword(string loginPass, string passwordHash)
    {
        return BCrypt.Net.BCrypt.Verify(loginPass, passwordHash);
    }

    public static bool IsStrongPassword(string password)
    {
        return PassRegex.IsMatch(password);
    }
}