using System.Security.Cryptography;
using Netina.Repository.Abstracts;

namespace Netina.Api.Services;

public class CurrentUserService(IHttpContextAccessor httpContextAccessor) : ICurrentUserService
{
    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 JwtSecurityToken? JwtToken => GetJwtToken();
    private JwtSecurityToken? GetJwtToken()
    {
        var stream = httpContextAccessor.HttpContext?.Request.Headers.Authorization.FirstOrDefault();
        if (stream == null)
            return null;
        var handler = new JwtSecurityTokenHandler();
        var jsonToken = handler.ReadToken(stream.Split(" ").Last());
        return jsonToken as JwtSecurityToken;
    }

    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;
    }



}