using System.Security.Claims;
using System.Security.Cryptography;

namespace NetinaCMS.Api.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? RoleName => _httpContextAccessor.HttpContext?.User?.FindFirstValue(ClaimTypes.Role);
    public string? UserName => _httpContextAccessor.HttpContext?.User?.FindFirstValue(ClaimTypes.Name);
    public string? DeviceId => GetDeviceId(_httpContextAccessor.HttpContext);
    public bool IsAuthorized => GetAuthorized();
    public List<string>? Permissions => _httpContextAccessor.HttpContext?.User?.FindAll("Permission")?.Select(c => c.Value)?.ToList();

    private string? GetDeviceId(HttpContext? context)
    {
        if (context?.Request?.Headers == null)
            return null;
        string? userAgent = context.Request.Headers["User-Agent"];
        string? ipAddress = context.Connection.RemoteIpAddress?.ToString();
        string? origin = context.Request.Headers["Origin"];
        string input = userAgent + "_" + ipAddress;

        using SHA256 sha256Hash = SHA256.Create();
        byte[] bytes = sha256Hash.ComputeHash(Encoding.UTF8.GetBytes(input));
        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < bytes.Length; i++)
        {
            builder.Append(bytes[i].ToString("x2"));
        }
        var uniqueId = builder.ToString();
        return uniqueId;
    }

    private bool GetAuthorized()
    {
        if (_httpContextAccessor.HttpContext?.User.Identity == null)
            return false;
        return _httpContextAccessor.HttpContext.User.Identity.IsAuthenticated;
    }


}