using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;

namespace WorkFlowCheck.BL.Static
{
    public static class CodeGenerator2F
    {
        private static readonly Random _random = new Random();
        private const string SecretKey = "874512WcfApplicationNuvolar.hu!%mBX210jUUKL";
        private static readonly byte[] KeyBytes = Encoding.UTF8.GetBytes(SecretKey);

        public static string GenerateSixDigitCode()
        {
            return _random.Next(100000, 1000000).ToString(); // 100000 - 999999
        }
        public static string GenerateToken2F(string value1, string value2, string value3)
        {
            var tokenHandler = new JwtSecurityTokenHandler();

            var claims = new[]
            {
            new Claim("val1", value1),
            new Claim("val2", value2),
            new Claim("val3", value3)
        };

            var descriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(claims),
                Expires = DateTime.UtcNow.AddSeconds(60 * 60 * 2),
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(KeyBytes), SecurityAlgorithms.HmacSha256Signature)
            };

            var token = tokenHandler.CreateToken(descriptor);
            return tokenHandler.WriteToken(token);
        }
        public static bool ValidateToken2F(string token, string expected1, string expected2, string expected3)
        {
            var tokenHandler = new JwtSecurityTokenHandler();

            try
            {
                var parameters = new TokenValidationParameters
                {
                    ValidateIssuer = false,
                    ValidateAudience = false,
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey = new SymmetricSecurityKey(KeyBytes),
                    ClockSkew = TimeSpan.Zero // nincs türelmi idő
                };

                var principal = tokenHandler.ValidateToken(token, parameters, out var validatedToken);

                var val1 = principal.FindFirst("val1")?.Value;
                var val2 = principal.FindFirst("val2")?.Value;
                var val3 = principal.FindFirst("val3")?.Value;

                return val1 == expected1 && val2 == expected2 && val3 == expected3;
            }
            catch
            {
                return false;
            }
        }
    }
}
