using MediatR;
using IamService.Domain.AggregatesModel.PrivilegedAccessAggregate;

namespace IamService.API.Application.Queries.PrivilegedAccess;

public class GetActivePrivilegedAccessQueryHandler : IRequestHandler<GetActivePrivilegedAccessQuery, IEnumerable<PrivilegedAccessDto>>
{
    private readonly IPrivilegedAccessRepository _repository;
    public GetActivePrivilegedAccessQueryHandler(IPrivilegedAccessRepository repository) => _repository = repository;

    public async Task<IEnumerable<PrivilegedAccessDto>> Handle(GetActivePrivilegedAccessQuery request, CancellationToken cancellationToken)
    {
        var grants = await _repository.GetActiveByUserIdAsync(request.UserId, cancellationToken);
        return grants.Select(g => new PrivilegedAccessDto(
            g.Id,
            g.UserId,
            g.RoleId,
            g.ResourceScope,
            g.Reason,
            g.Status.Name,
            g.StartsAt,
            g.ExpiresAt,
            g.GrantedByUserId));
    }
}
