namespace CMSMicroservice.Application.ConfigurationCQ.Queries.GetAllConfigurations;

public class GetAllConfigurationsQueryHandler : IRequestHandler<GetAllConfigurationsQuery, GetAllConfigurationsResponseDto>
{
    private readonly IApplicationDbContext _context;

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

    public async Task<GetAllConfigurationsResponseDto> Handle(GetAllConfigurationsQuery request, CancellationToken cancellationToken)
    {
        var query = _context.SystemConfigurations
            .ApplyOrder(sortBy: request.SortBy)
            .AsNoTracking()
            .AsQueryable();

        if (request.Filter is not null)
        {
            query = query
                .Where(x => request.Filter.Scope == null || x.Scope == request.Filter.Scope)
                .Where(x => request.Filter.KeyContains == null || x.Key.Contains(request.Filter.KeyContains))
                .Where(x => request.Filter.IsActive == null || x.IsActive == request.Filter.IsActive);
        }

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

        var models = await query
            .PaginatedListAsync(paginationState: request.PaginationState)
            .Select(x => new GetAllConfigurationsResponseModel
            {
                Id = x.Id,
                Scope = x.Scope,
                Key = x.Key,
                Value = x.Value,
                Description = x.Description,
                IsActive = x.IsActive,
                Created = x.Created,
                LastModified = x.LastModified
            })
            .ToListAsync(cancellationToken);

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