using Microsoft.JSInterop;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;

namespace OnProfNext.Client.Services
{
    public class AuthService
    {
        private readonly IJSRuntime _js;
        private const string TokenKey = "authToken";

        public AuthService(IJSRuntime js) => _js = js;

        public ValueTask SaveTokenAsync(string token) =>
            _js.InvokeVoidAsync("localStorage.setItem", TokenKey, token);

        public ValueTask<string?> GetTokenAsync() =>
            _js.InvokeAsync<string?>("localStorage.getItem", TokenKey);

        public ValueTask LogoutAsync() =>
            _js.InvokeVoidAsync("localStorage.removeItem", TokenKey);

        public async Task<string?> GetUsernameAsync()
        {
            var token = await GetTokenAsync();
            if (string.IsNullOrWhiteSpace(token))
            {
                return null;
            }
            try
            {
                var handler = new JwtSecurityTokenHandler();
                var jwt = handler.ReadJwtToken(token);
                var usernameClaim = jwt.Claims.FirstOrDefault(c =>
                    c.Type == ClaimTypes.Name ||
                    c.Type == "unique_name" ||
                    c.Type == "name"
                );
                return usernameClaim?.Value;
            }
            catch
            {
                return null;
            }
        }

        public async Task<bool> IsLoggedInAsync()
        {
            var token = await GetTokenAsync();
            if (string.IsNullOrWhiteSpace(token))
            {
                return false;
            }

            try
            {
                var handler = new JwtSecurityTokenHandler();
                var jwt = handler.ReadJwtToken(token);
                var exp = jwt.ValidTo;
                return exp > DateTime.UtcNow;
            }
            catch
            {
                return false;
            }
        }
    }
}