using MilitaryTrainingManagement.Models.Enums;
using MilitaryTrainingManagement.Services.Interfaces;

namespace MilitaryTrainingManagement.Authorization;

/// <summary>
/// 组织层级授权服务实现
/// </summary>
public class OrganizationalAuthorizationService : IOrganizationalAuthorizationService
{
    private readonly IOrganizationService _organizationService;

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

    public async Task<bool> CanAccessUnitAsync(int userUnitId, int targetUnitId)
    {
        return await _organizationService.IsUnitOrSubordinateAsync(userUnitId, targetUnitId);
    }

    public bool HasMinimumLevel(OrganizationalLevel userLevel, OrganizationalLevel minimumLevel)
    {
        // 层级数值越小表示层级越高（Division=1 > Regiment=2 > Battalion=3 > Company=4）
        return (int)userLevel <= (int)minimumLevel;
    }

    public async Task<IEnumerable<int>> GetAccessibleUnitIdsAsync(int userUnitId)
    {
        var subordinateIds = await _organizationService.GetAllSubordinateIdsAsync(userUnitId);
        return new[] { userUnitId }.Concat(subordinateIds);
    }

    public async Task<bool> IsAncestorUnitAsync(int targetUnitId, int currentUnitId)
    {
        // 检查 targetUnitId 是否是 currentUnitId 的上级单位
        var ancestorIds = await _organizationService.GetAllAncestorIdsAsync(currentUnitId);
        return ancestorIds.Contains(targetUnitId);
    }
}
