namespace CMSMicroservice.Application.ConfigurationCQ.Commands.SetConfigurationValue;

public class SetConfigurationValueCommandHandler : IRequestHandler<SetConfigurationValueCommand, long>
{
    private readonly IApplicationDbContext _context;
    private readonly ICurrentUserService _currentUser;

    public SetConfigurationValueCommandHandler(
        IApplicationDbContext context,
        ICurrentUserService currentUser)
    {
        _context = context;
        _currentUser = currentUser;
    }

    public async Task<long> Handle(SetConfigurationValueCommand request, CancellationToken cancellationToken)
    {
        // بررسی وجود Configuration با همین Scope و Key
        var existingConfig = await _context.SystemConfigurations
            .FirstOrDefaultAsync(x => 
                x.Scope == request.Scope && 
                x.Key == request.Key, 
                cancellationToken);

        SystemConfiguration entity;
        bool isNewRecord = existingConfig == null;
        string oldValue = null;

        if (isNewRecord)
        {
            // ایجاد Configuration جدید
            entity = new SystemConfiguration
            {
                Scope = request.Scope,
                Key = request.Key,
                Value = request.Value,
                Description = request.Description,
                IsActive = true
            };

            await _context.SystemConfigurations.AddAsync(entity, cancellationToken);
        }
        else
        {
            // به‌روزرسانی Configuration موجود
            entity = existingConfig;
            oldValue = entity.Value;

            entity.Value = request.Value;
            
            if (!string.IsNullOrEmpty(request.Description))
            {
                entity.Description = request.Description;
            }

            _context.SystemConfigurations.Update(entity);
        }

        await _context.SaveChangesAsync(cancellationToken);

        // ثبت تاریخچه
        var history = new SystemConfigurationHistory
        {
            ConfigurationId = entity.Id,
            Scope = entity.Scope,
            Key = entity.Key,
            OldValue = oldValue,
            NewValue = entity.Value,
            Reason = request.ChangeReason ?? (isNewRecord ? "Initial creation" : "Value updated"),
            PerformedBy = "System" // TODO: باید از Current User گرفته شود
        };

        await _context.SystemConfigurationHistories.AddAsync(history, cancellationToken);
        await _context.SaveChangesAsync(cancellationToken);

        return entity.Id;
    }
}
