using IWS5.Core.Exceptions;
using System.IdentityModel.Tokens.Jwt;
using Microsoft.AspNetCore.Mvc;

namespace IWS5.Api.OptionsSetup;

internal static class JwtTokenHelper
{
    internal static string GetUserName(HttpContext context, ILogger logger, out IActionResult actionResult)
    {
        string userName;
        try
        {
            userName = GetUserEmailFromToken(context);
        }
        catch (InvalidTokenException ex)
        {
            logger.LogError(ex, "Error retrieving user email from token");
            actionResult = new UnauthorizedObjectResult(new { message = "Invalid or missing token", error = ex.Message });
            userName = null;
        }

        actionResult = null;
        return userName;
    }
    
    internal static string GetUserEmailFromToken(HttpContext httpContext)
    {
        var token = httpContext.Request.Headers.Authorization.ToString().Replace("Bearer ", string.Empty);

        var handler = new JwtSecurityTokenHandler();
        var jwtToken = handler.ReadJwtToken(token);

        var emailClaim = jwtToken.Claims.FirstOrDefault(claim => claim.Type == "email");

        return emailClaim?.Value ?? throw new InvalidTokenException("Email claim not found in token.");
    }
}