namespace CMSMicroservice.Application.NetworkMembershipCQ.Queries.GetNetworkMembershipHistory;

public class GetNetworkMembershipHistoryQueryHandler : IRequestHandler<GetNetworkMembershipHistoryQuery, GetNetworkMembershipHistoryResponseDto>
{
    private readonly IApplicationDbContext _context;

    public GetNetworkMembershipHistoryQueryHandler(IApplicationDbContext context)
    {
        _context = context;
    }

    public async Task<GetNetworkMembershipHistoryResponseDto> Handle(GetNetworkMembershipHistoryQuery request, CancellationToken cancellationToken)
    {
        var query = _context.NetworkMembershipHistories
            .AsNoTracking()
            .AsQueryable();

        if (request.UserId.HasValue)
        {
            query = query.Where(x => x.UserId == request.UserId.Value);
        }

        query = query.ApplyOrder(sortBy: request.SortBy ?? "Created");

        var meta = await query.GetMetaData(request.PaginationState, cancellationToken);

        var models = await query
            .PaginatedListAsync(paginationState: request.PaginationState)
            .Select(x => new GetNetworkMembershipHistoryResponseModel
            {
                Id = x.Id,
                UserId = x.UserId,
                OldParentId = x.OldParentId,
                NewParentId = x.NewParentId,
                OldLegPosition = x.OldLegPosition,
                NewLegPosition = x.NewLegPosition,
                Action = x.Action,
                Reason = x.Reason,
                PerformedBy = x.PerformedBy,
                Created = x.Created
            })
            .ToListAsync(cancellationToken);

        return new GetNetworkMembershipHistoryResponseDto
        {
            MetaData = meta,
            Models = models
        };
    }
}
