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

namespace HoneyBox.Admin.Filters;

/// <summary>
/// 管理员认证过滤器
/// </summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false)]
public class AdminAuthAttribute : Attribute, IAuthorizationFilter
{
    /// <summary>
    /// 执行认证检查
    /// </summary>
    public void OnAuthorization(AuthorizationFilterContext context)
    {
        // 检查是否有 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 _))
        {
            context.Result = new JsonResult(ApiResponse.Error(AdminErrorCodes.TokenInvalid, "无效的用户身份"))
            {
                StatusCode = StatusCodes.Status401Unauthorized
            };
        }
    }
}
