using System.Security.Claims;
using CMSMicroservice.Application.Common.Interfaces;
using Microsoft.AspNetCore.Http;

namespace CMSMicroservice.WebApi.Common.Services;

public class CurrentUserService : ICurrentUserService
{
    private readonly IHttpContextAccessor _httpContextAccessor;

    public CurrentUserService(IHttpContextAccessor httpContextAccessor)
    {
        _httpContextAccessor = httpContextAccessor;
    }

    public string? UserId => _httpContextAccessor.HttpContext?.User?.FindFirstValue(ClaimTypes.NameIdentifier);

    public string? Username => _httpContextAccessor.HttpContext?.User?.FindFirstValue(ClaimTypes.Name)
                               ?? _httpContextAccessor.HttpContext?.User?.FindFirstValue(ClaimTypes.Email);

    public bool IsAuthenticated => _httpContextAccessor.HttpContext?.User?.Identity?.IsAuthenticated ?? false;

    public string GetPerformedBy()
    {
        if (!IsAuthenticated || string.IsNullOrEmpty(UserId))
            return "System";

        return string.IsNullOrEmpty(Username)
            ? $"User:{UserId}"
            : $"{UserId}:{Username}";
    }
}
