using Microsoft.AspNetCore.Authorization;
using MilitaryTrainingManagement.Models.Enums;
using MilitaryTrainingManagement.Services.Interfaces;

namespace MilitaryTrainingManagement.Authorization;

/// <summary>
/// 组织层级授权处理器 - 验证用户是否具有所需的组织层级权限
/// </summary>
public class OrganizationalLevelAuthorizationHandler : AuthorizationHandler<OrganizationalLevelRequirement>
{
    protected override Task HandleRequirementAsync(
        AuthorizationHandlerContext context,
        OrganizationalLevelRequirement requirement)
    {
        var unitLevelClaim = context.User.FindFirst("unitLevel");
        if (unitLevelClaim == null || !int.TryParse(unitLevelClaim.Value, out var userLevel))
        {
            return Task.CompletedTask;
        }

        // 层级数值越小表示层级越高（Division=1 > Regiment=2 > Battalion=3 > Company=4）
        // 用户层级必须小于或等于要求的最低层级
        if (userLevel <= (int)requirement.MinimumLevel)
        {
            context.Succeed(requirement);
        }

        return Task.CompletedTask;
    }
}

/// <summary>
/// 组织资源授权处理器 - 验证用户是否可以访问特定组织单位的资源
/// </summary>
public class OrganizationalResourceAuthorizationHandler : AuthorizationHandler<OrganizationalResourceRequirement, int>
{
    private readonly IOrganizationService _organizationService;

    public OrganizationalResourceAuthorizationHandler(IOrganizationService organizationService)
    {
        _organizationService = organizationService;
    }

    protected override async Task HandleRequirementAsync(
        AuthorizationHandlerContext context,
        OrganizationalResourceRequirement requirement,
        int targetUnitId)
    {
        var unitIdClaim = context.User.FindFirst("unitId");
        if (unitIdClaim == null || !int.TryParse(unitIdClaim.Value, out var userUnitId))
        {
            return;
        }

        // 检查目标单位是否是用户单位本身或其下级单位
        if (await _organizationService.IsUnitOrSubordinateAsync(userUnitId, targetUnitId))
        {
            context.Succeed(requirement);
        }
    }
}
