using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using System.Text.Json;
using API_Access_Control.Models.Requests;
using API_Access_Control.Models.Responses;
using API_Access_Control.Models.Responses.Errors;
using API_Access_Control.Services;
using Microsoft.IdentityModel.Tokens;

namespace API_Access_Control.Handlers;

public class ValidatorHandler
{
    public static object HandleRequest(JWTValidationRequest request, ApiService apiService)
    {
        int apiId = request.ApiId;
        string apiSecret = request.ApiSecret;

        // Checking if the apiId and the apiSecret exist in the database
        if (!apiService.Exists(apiId, apiSecret))
        {
            object jsonMsg = new BadRequest
            {
                Message = "Invalid request body",
                Details = "apiId and apiSecret combination invalid, not found or malformed"
            };
            return Results.BadRequest(jsonMsg);
        }

        string token = request.Token;
        string secretKey = GetSecretKey();

        return ValidateJWT(token, secretKey);
    }
    private static object ValidateJWT(string token, string secretKey)
    {
        // Create a new token handler
        var tokenHandler = new System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler();

        // Create a new token validation parameters
        var validationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters
        {
            ValidateIssuerSigningKey = true,
            IssuerSigningKey = new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(System.Text.Encoding.UTF8.GetBytes(secretKey)),
            ValidateIssuer = false,
            ValidateAudience = false,
            ValidateLifetime = true,
            ClockSkew = System.TimeSpan.Zero
        };

        try
        {
            // Validate the token
            tokenHandler.ValidateToken(token, validationParameters, out var validatedToken);

            // If the token is valid, return a JSON object
            return new JWTValidationResponse { Validity = true };
        }
        catch
        {
            // If the token is not valid, return a JSON object
            return new JWTValidationResponse { Validity = false };

        }
    }

    private static string GetSecretKey()
    {
        return "0123456789ABCDEF0123456789ABCDEF"; // 32 bits for HMAC SHA-256
    }
}