using System.Security.Claims;
using Microsoft.AspNetCore.Mvc;

namespace MealPlan.Api.Extensions;

public static class ClaimsPrincipalExtensions
{
    public static Guid? GetUserId(this ClaimsPrincipal user)
    {
        var raw = user.FindFirstValue(ClaimTypes.NameIdentifier)
                  ?? user.FindFirstValue("sub");
        return Guid.TryParse(raw, out var id) ? id : null;
    }

    public static IActionResult? RequireUserId(this ClaimsPrincipal user, out Guid userId)
    {
        var id = user.GetUserId();
        if (id is null)
        {
            userId = Guid.Empty;
            return new UnauthorizedResult();
        }

        userId = id.Value;
        return null;
    }
}
