namespace CMSMicroservice.Application.ConfigurationCQ.Queries.GetConfigurationByKey;

public class GetConfigurationByKeyQueryHandler : IRequestHandler<GetConfigurationByKeyQuery, ConfigurationDto?>
{
    private readonly IApplicationDbContext _context;

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

    public async Task<ConfigurationDto?> Handle(GetConfigurationByKeyQuery request, CancellationToken cancellationToken)
    {
        var config = await _context.SystemConfigurations
            .AsNoTracking()
            .Where(x => x.Scope == request.Scope && x.Key == request.Key)
            .FirstOrDefaultAsync(cancellationToken);

        if (config == null)
            return null;

        return new ConfigurationDto
        {
            Id = config.Id,
            Scope = config.Scope,
            Key = config.Key,
            Value = config.Value,
            Description = config.Description,
            IsActive = config.IsActive,
            Created = config.Created,
            LastModified = config.LastModified
        };
    }
}
