using System.Security.Claims;
using HoneyBox.Admin.Business.Attributes;
using HoneyBox.Admin.Models.Common;
using HoneyBox.Admin.Services;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;

namespace HoneyBox.Admin.Filters;

/// <summary>
/// 业务模块权限验证过滤器
/// 处理 BusinessPermissionAttribute 标记的权限验证
/// </summary>
public class BusinessPermissionFilter : IAsyncAuthorizationFilter
{
    private readonly IPermissionService _permissionService;

    public BusinessPermissionFilter(IPermissionService permissionService)
    {
        _permissionService = permissionService;
    }

    public async Task OnAuthorizationAsync(AuthorizationFilterContext context)
    {
        // 获取 BusinessPermissionAttribute
        var permissionAttributes = context.ActionDescriptor.EndpointMetadata
            .OfType<BusinessPermissionAttribute>()
            .ToList();

        if (!permissionAttributes.Any())
        {
            return; // 没有权限标记，跳过验证
        }

        // 检查是否有 AllowAnonymous 特性
        var allowAnonymous = context.ActionDescriptor.EndpointMetadata
            .Any(em => em is Microsoft.AspNetCore.Authorization.AllowAnonymousAttribute);

        if (allowAnonymous)
        {
            return;
        }

        // 检查用户是否已认证
        var user = context.HttpContext.User;
        if (user?.Identity?.IsAuthenticated != true)
        {
            context.Result = new JsonResult(ApiResponse.Error(AdminErrorCodes.TokenInvalid, "未授权访问"))
            {
                StatusCode = StatusCodes.Status401Unauthorized
            };
            return;
        }

        // 获取用户ID
        var userIdClaim = user.FindFirst(ClaimTypes.NameIdentifier);
        if (userIdClaim == null || !long.TryParse(userIdClaim.Value, out var userId))
        {
            context.Result = new JsonResult(ApiResponse.Error(AdminErrorCodes.TokenInvalid, "无效的用户身份"))
            {
                StatusCode = StatusCodes.Status401Unauthorized
            };
            return;
        }

        // 检查所有权限
        foreach (var attr in permissionAttributes)
        {
            var hasPermission = await _permissionService.HasPermissionAsync(userId, attr.PermissionCode);
            if (!hasPermission)
            {
                context.Result = new JsonResult(ApiResponse.Error(AdminErrorCodes.PermissionDenied, $"没有操作权限: {attr.PermissionCode}"))
                {
                    StatusCode = StatusCodes.Status403Forbidden
                };
                return;
            }
        }
    }
}
