using System.Security.Claims;
using CashLineERP.SharedKernel.Identity;

namespace CashLineERP.Api.Infrastructure;

internal static class CurrentUserAccessor
{
    public static long GetRequiredUserId(ClaimsPrincipal user)
    {
        var claimValue = user.FindFirstValue(ClaimTypes.NameIdentifier);
        if (!long.TryParse(claimValue, out var userId))
        {
            throw new InvalidOperationException("Authenticated user context is missing a valid user ID.");
        }

        return userId;
    }

    public static void EnsureInternalUser(ClaimsPrincipal user)
    {
        if (!string.Equals(user.FindFirstValue(ApiClaimTypes.UserType), UserTypeCode.Internal, StringComparison.OrdinalIgnoreCase))
        {
            throw new InvalidOperationException("This operation requires an internal authenticated user.");
        }
    }

    public static void EnsureExternalPartyAccess(ClaimsPrincipal user, long requestedPartyId)
    {
        if (!string.Equals(user.FindFirstValue(ApiClaimTypes.UserType), UserTypeCode.External, StringComparison.OrdinalIgnoreCase))
        {
            throw new InvalidOperationException("This operation requires an external authenticated user.");
        }

        var claimValue = user.FindFirstValue(ApiClaimTypes.PartyId);
        if (!long.TryParse(claimValue, out var partyId) || partyId != requestedPartyId)
        {
            throw new InvalidOperationException("Authenticated external user is not allowed to access the requested party context.");
        }
    }
}
