namespace CMSMicroservice.Application.ConfigurationCQ.Commands.DeactivateConfiguration;

public class DeactivateConfigurationCommandHandler : IRequestHandler<DeactivateConfigurationCommand, Unit>
{
    private readonly IApplicationDbContext _context;
    private readonly ICurrentUserService _currentUser;

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

    public async Task<Unit> Handle(DeactivateConfigurationCommand request, CancellationToken cancellationToken)
    {
        var entity = await _context.SystemConfigurations
            .FirstOrDefaultAsync(x => x.Id == request.ConfigurationId, cancellationToken)
            ?? throw new NotFoundException(nameof(SystemConfiguration), request.ConfigurationId);

        // اگر از قبل غیرفعال است، خطا ندهیم
        if (!entity.IsActive)
        {
            return Unit.Value;
        }

        var oldValue = entity.Value;
        entity.IsActive = false;

        _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.Reason ?? "Configuration deactivated",
            PerformedBy = _currentUser.GetPerformedBy()
        };

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

        return Unit.Value;
    }
}
