using Microsoft.AspNetCore.Authorization;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using Fuel.Application.Service;
using Microsoft.AspNetCore.Http;

namespace Fuel.Application.Authorization
{
    public class PermissionHandler : AuthorizationHandler<PermissionRequirement>
    {
        private readonly IUserService _userService;

        public PermissionHandler(IUserService userService)
        {
            _userService = userService;
        }

        protected override async Task HandleRequirementAsync(AuthorizationHandlerContext context, PermissionRequirement requirement)
        {
            bool IsSite = false;//判断是否是子站请求
            bool Isbackstage = false;//判断是否是后台请求
            string secret_id = string.Empty;
            var httpContext = (context.Resource as HttpContext);
            if (httpContext != null)
            {
                if (httpContext.Request.Headers.TryGetValue("secret_id", out var userIdHeader))
                {
                    IsSite = true;
                     secret_id = userIdHeader.ToString();
                }
            }

            var user = context.User;
            int userId = 0;
            if (user != null && user.Identity.IsAuthenticated)
            {
                // 从用户声明中获取用户 ID
                var userIdClaim = user.FindFirst(ClaimTypes.NameIdentifier);
                if (userIdClaim != null)
                {
                    userId = int.TryParse(userIdClaim.Value, out int number) ? number : 0;
                    Isbackstage = true;
                }
            }

            if (IsSite || Isbackstage)
            {
                List<string>? permissions = null;
                if (IsSite)
                {
                    // 查询用户权限
                    permissions = _userService.GetUserPermissions(userId);
                }
                if (Isbackstage)
                {

                    permissions = _userService.GetSitePermissions(secret_id);
                }

                // 检查用户是否有权限
                if (permissions.Contains(requirement.Permission))
                {
                    context.Succeed(requirement);
                }
            }
          
        }
    }
}
