using Atomx.Common.Utils;
using Microsoft.AspNetCore.Components.Authorization;
using System.Net.Http.Json;
using System.Security.Claims;

namespace Atomx.Admin.Client.Services
{
    public interface IPermissionService
    {
        /// <summary>
        /// 是否拥有权限点
        /// </summary>
        /// <param name="permission"></param>
        /// <returns></returns>
        Task<bool> HasPermissionAsync(string permission);

       /// <summary>
       /// 是否拥有指定权限中的一个
       /// </summary>
       /// <param name="permissions"></param>
       /// <returns></returns>
        Task<bool> HasAnyPermissionAsync(params string[] permissions);

        /// <summary>
        /// 是否拥有指定权限中的所有权限
        /// </summary>
        /// <param name="permissions"></param>
        /// <returns></returns>
        Task<bool> HasAllPermissionsAsync(params string[] permissions);

        /// <summary>
        /// 获取用户的所有权限
        /// </summary>
        /// <returns></returns>
        Task<List<string>> GetUserPermissionsAsync();
        //Task<List<string>> GetUserRolesAsync();
    }

    public class ClientPermissionService : IPermissionService
    {
        private readonly AuthenticationStateProvider _authenticationStateProvider;
        private readonly HttpClient _httpClient;

        public ClientPermissionService(
            AuthenticationStateProvider authenticationStateProvider,
            HttpClient httpClient)
        {
            _authenticationStateProvider = authenticationStateProvider;
            _httpClient = httpClient;
        }

        public async Task<bool> HasPermissionAsync(string permission)
        {
            // 客户端检查（基于声明）
            var authState = await _authenticationStateProvider.GetAuthenticationStateAsync();
            var user = authState.User;

            if (!user.Identity?.IsAuthenticated ?? true)
                return false;

            // 检查声明中的权限
            var hasPermission = user.Claims.Any(c =>
                c.Type == ClaimKeys.Permission && c.Value == permission);

            if (hasPermission)
                return true;

            // 如果声明中没有，调用API验证
            //try
            //{
            //    return await _httpClient.GetFromJsonAsync<bool>($"/api/auth/haspermission?permission={permission}");
            //}
            //catch
            //{
            //    return false;
            //}
            return false;
        }

        public async Task<bool> HasAnyPermissionAsync(params string[] permissions)
        {
            foreach (var permission in permissions)
            {
                if (await HasPermissionAsync(permission))
                    return true;
            }
            return false;
        }

        public async Task<bool> HasAllPermissionsAsync(params string[] permissions)
        {
            foreach (var permission in permissions)
            {
                if (!await HasPermissionAsync(permission))
                    return false;
            }
            return true;
        }

        public async Task<List<string>> GetUserPermissionsAsync()
        {
            try
            {
                return await _httpClient.GetFromJsonAsync<List<string>>("/api/auth/permissions")
                    ?? new List<string>();
            }
            catch
            {
                return new List<string>();
            }
        }

        public async Task<List<string>> GetUserRolesAsync()
        {
            var authState = await _authenticationStateProvider.GetAuthenticationStateAsync();
            var user = authState.User;

            return user.Claims
                .Where(c => c.Type == ClaimTypes.Role)
                .Select(c => c.Value)
                .ToList();
        }
    }
}