#nullable enable
using System.Security.Claims;
using Baya.Application.Contracts.Common;
using Baya.SharedKernel.Extensions;
using Microsoft.AspNetCore.Http;

namespace Baya.Infrastructure.Identity.Identity.CurrentUser;

/// <summary>
/// Resolves the current user from the active HTTP request's claims. When there is no request or no
/// authenticated principal (background work, startup), all members report "no user".
/// </summary>
public sealed class HttpContextCurrentUser(IHttpContextAccessor httpContextAccessor) : ICurrentUser
{
    private ClaimsPrincipal? Principal => httpContextAccessor.HttpContext?.User;

    public int? UserId
    {
        get
        {
            var rawId = Principal?.Identity?.GetUserId();
            return rawId.HasValue() && int.TryParse(rawId, out var id) ? id : null;
        }
    }

    public bool IsAuthenticated => Principal?.Identity?.IsAuthenticated ?? false;

    public IReadOnlyList<string> Roles =>
        Principal?.FindAll(ClaimTypes.Role).Select(c => c.Value).ToArray() ?? [];

    public string? IpAddress =>
        httpContextAccessor.HttpContext?.Connection.RemoteIpAddress?.ToString();
}
