using Mirea.Api.Security.Common.Model;
using System.Linq;
using System.Security;

namespace Mirea.Api.Security.Services;

public class PasswordPolicyService(PasswordPolicy policy)
{
    public void ValidatePasswordOrThrow(string password)
    {
        if (password.Length < policy.MinimumLength)
            throw new SecurityException($"Password must be at least {policy.MinimumLength} characters long.");

        if (policy.RequireLetter && !password.Any(char.IsLetter))
            throw new SecurityException("Password must contain at least one letter.");

        if (policy.RequireLettersDifferentCase && !password.Any(char.IsLower) && !password.Any(char.IsUpper))
            throw new SecurityException("Password must contain at least one lowercase and uppercase letter.");

        if (policy.RequireDigit && !password.Any(char.IsDigit))
            throw new SecurityException("Password must contain at least one digit.");

        if (policy.RequireSpecialCharacter && password.All(char.IsLetterOrDigit))
            throw new SecurityException("Password must contain at least one special character.");
    }

    public bool TryValidatePassword(string password)
    {
        try
        {
            ValidatePasswordOrThrow(password);
        }
        catch
        {
            return false;
        }

        return true;
    }
}