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 GeneratorHandler
{
    public static object HandleRequest(JWTGenerationRequest request, ConsommateurService consommateurService)
    {
        int callerId = request.CallerId;
        string callerSecret = request.CallerSecret;

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

        string secretKey = GetSecretKey();
        
        return GenerateJWT(secretKey);
    }
    private static object GenerateJWT(string secretKey)
    {
        // Set the token expiration time
        DateTime tokenExpiration = DateTime.UtcNow.AddHours(1);

        // Create a new security token handler
        var tokenHandler = new JwtSecurityTokenHandler();

        // Create a new token descriptor
        var tokenDescriptor = new SecurityTokenDescriptor
        {
            Subject = new ClaimsIdentity(new[] { new Claim("username", "john_doe") }),
            Expires = tokenExpiration,
            SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secretKey)), SecurityAlgorithms.HmacSha256Signature)
        };

        // Create the token
        var token = tokenHandler.CreateToken(tokenDescriptor);

        // Return the token as a JSON object
        return new JWTGenerationResponse { AccessToken = tokenHandler.WriteToken(token) };
    }

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