using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Tiku.Application.Security; namespace Tiku.Infrastructure.Tenancy; public sealed class TenantExecutionScope( IServiceScopeFactory scopeFactory, ILogger logger) : ITenantExecutionScope { public Task ExecuteAsync( Guid? targetTenantId, string reason, Func operation, CancellationToken cancellationToken = default) { return ExecuteAsync( targetTenantId, reason, async (provider, token) => { await operation(provider, token); return null; }, cancellationToken); } public async Task ExecuteAsync( Guid? targetTenantId, string reason, Func> operation, CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(operation); if (string.IsNullOrWhiteSpace(reason)) { throw new ArgumentException("A system scope requires an audit reason.", nameof(reason)); } await using var scope = scopeFactory.CreateAsyncScope(); var initializer = scope.ServiceProvider.GetRequiredService(); initializer.InitializeSystem(targetTenantId, reason); logger.LogWarning( "Entering audited system tenant scope. TargetTenantId={TargetTenantId} Reason={Reason}", targetTenantId, reason); return await operation(scope.ServiceProvider, cancellationToken); } }