namespace CMSMicroservice.Application.ConfigurationCQ.Queries.GetConfigurationHistory;

public class GetConfigurationHistoryQueryHandler : IRequestHandler<GetConfigurationHistoryQuery, GetConfigurationHistoryResponseDto>
{
    private readonly IApplicationDbContext _context;

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

    public async Task<GetConfigurationHistoryResponseDto> Handle(GetConfigurationHistoryQuery request, CancellationToken cancellationToken)
    {
        // بررسی وجود Configuration
        var configExists = await _context.SystemConfigurations
            .AnyAsync(x => x.Id == request.ConfigurationId, cancellationToken);

        if (!configExists)
        {
            throw new NotFoundException(nameof(SystemConfiguration), request.ConfigurationId);
        }

        var query = _context.SystemConfigurationHistories
            .Where(x => x.ConfigurationId == request.ConfigurationId)
            .ApplyOrder(sortBy: request.SortBy ?? "-Created") // پیش‌فرض: جدیدترین اول
            .AsNoTracking()
            .AsQueryable();

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

        var models = await query
            .PaginatedListAsync(paginationState: request.PaginationState)
            .Select(x => new GetConfigurationHistoryResponseModel
            {
                Id = x.Id,
                ConfigurationId = x.ConfigurationId,
                Scope = x.Scope,
                Key = x.Key,
                OldValue = x.OldValue,
                NewValue = x.NewValue,
                ChangeReason = x.Reason,
                ChangedBy = x.PerformedBy,
                Created = x.Created
            })
            .ToListAsync(cancellationToken);

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