/*
 * File: ShadowedRealms.Data/UnitOfWork.cs
 * Created: 2025-10-19
 * Last Modified: 2025-10-22
 * Description: Unit of Work implementation providing transaction coordination across all repositories,
 *              lifecycle management, and bulk operations with kingdom-scoped security integration.
 * Last Edit Notes: Fixed all compilation errors to match IUnitOfWork interface exactly with comprehensive implementation
 */

using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Storage;
using Microsoft.Extensions.Logging;
using ShadowedRealms.Core.Interfaces;
using ShadowedRealms.Core.Interfaces.Repositories;
using ShadowedRealms.Core.Models.Combat;
using ShadowedRealms.Core.Models.Purchase;
using ShadowedRealms.Data.Contexts;
using ShadowedRealms.Data.Repositories.Alliance;
using ShadowedRealms.Data.Repositories.Combat;
using ShadowedRealms.Data.Repositories.Kingdom;
using ShadowedRealms.Data.Repositories.Player;
using ShadowedRealms.Data.Repositories.Purchase;
using System.Data;

namespace ShadowedRealms.Data
{
    /// <summary>
    /// Unit of Work implementation providing centralized transaction management and repository coordination.
    /// Ensures data consistency across all game systems while maintaining kingdom-scoped security.
    /// </summary>
    public class UnitOfWork : IUnitOfWork, IDisposable
    {
        private readonly GameDbContext _context;
        private readonly ILogger<UnitOfWork> _logger;
        private readonly ILoggerFactory _loggerFactory;
        private IDbContextTransaction? _transaction;
        private bool _disposed = false;
        private DateTime? _transactionStartTime;
        private IsolationLevel? _currentIsolationLevel;
        private int? _transactionKingdomId;

        // Repository instances - lazy loaded
        private IKingdomRepository? _kingdomRepository;
        private IPlayerRepository? _playerRepository;
        private IAllianceRepository? _allianceRepository;
        private ICombatLogRepository? _combatLogRepository;
        private IPurchaseLogRepository? _purchaseLogRepository;

        public UnitOfWork(GameDbContext context, ILogger<UnitOfWork> logger, ILoggerFactory loggerFactory)
        {
            _context = context ?? throw new ArgumentNullException(nameof(context));
            _logger = logger ?? throw new ArgumentNullException(nameof(logger));
            _loggerFactory = loggerFactory ?? throw new ArgumentNullException(nameof(loggerFactory));
        }

        #region Repository Access Properties

        /// <summary>
        /// Gets the Kingdom repository instance
        /// </summary>
        public IKingdomRepository Kingdoms
        {
            get
            {
                _kingdomRepository ??= new KingdomRepository(_context,
                    _loggerFactory.CreateLogger<KingdomRepository>());
                return _kingdomRepository;
            }
        }

        /// <summary>
        /// Gets the Player repository instance
        /// </summary>
        public IPlayerRepository Players
        {
            get
            {
                _playerRepository ??= new PlayerRepository(_context,
                    _loggerFactory.CreateLogger<PlayerRepository>());
                return _playerRepository;
            }
        }

        /// <summary>
        /// Gets the Alliance repository instance
        /// </summary>
        public IAllianceRepository Alliances
        {
            get
            {
                _allianceRepository ??= new AllianceRepository(_context,
                    _loggerFactory.CreateLogger<AllianceRepository>());
                return _allianceRepository;
            }
        }

        /// <summary>
        /// Gets the CombatLog repository instance
        /// </summary>
        public ICombatLogRepository CombatLogs
        {
            get
            {
                _combatLogRepository ??= new CombatLogRepository(_context,
                    _loggerFactory.CreateLogger<CombatLogRepository>());
                return _combatLogRepository;
            }
        }

        /// <summary>
        /// Gets the PurchaseLog repository instance
        /// </summary>
        public IPurchaseLogRepository PurchaseLogs
        {
            get
            {
                _purchaseLogRepository ??= new PurchaseLogRepository(_context,
                    _loggerFactory.CreateLogger<PurchaseLogRepository>());
                return _purchaseLogRepository;
            }
        }

        #endregion

        #region Transaction Management

        /// <summary>
        /// Begins a new database transaction for coordinated operations
        /// </summary>
        public async Task BeginTransactionAsync(IsolationLevel isolationLevel = IsolationLevel.ReadCommitted,
            int? kingdomId = null, CancellationToken cancellationToken = default)
        {
            try
            {
                if (_transaction != null)
                {
                    _logger.LogWarning("Transaction already active - disposing existing transaction before beginning new one");
                    await _transaction.DisposeAsync();
                }

                if (kingdomId.HasValue && kingdomId <= 0)
                    throw new ArgumentException("Kingdom ID must be positive", nameof(kingdomId));

                _transaction = await _context.Database.BeginTransactionAsync(isolationLevel, cancellationToken);
                _transactionStartTime = DateTime.UtcNow;
                _currentIsolationLevel = isolationLevel;
                _transactionKingdomId = kingdomId;

                _logger.LogDebug("Database transaction started: {TransactionId}, IsolationLevel: {IsolationLevel}, Kingdom: {KingdomId}",
                    _transaction.TransactionId, isolationLevel, kingdomId);
            }
            catch (OperationCanceledException)
            {
                _logger.LogDebug("Begin transaction operation cancelled");
                throw;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error beginning database transaction");
                throw new InvalidOperationException("Failed to begin database transaction", ex);
            }
        }

        /// <summary>
        /// Commits the current transaction and saves all changes
        /// </summary>
        public async Task CommitTransactionAsync(CancellationToken cancellationToken = default)
        {
            try
            {
                if (_transaction == null)
                {
                    throw new InvalidOperationException("No active transaction to commit");
                }

                await _context.SaveChangesAsync(cancellationToken);
                await _transaction.CommitAsync(cancellationToken);

                var duration = _transactionStartTime.HasValue ? DateTime.UtcNow - _transactionStartTime.Value : TimeSpan.Zero;
                _logger.LogDebug("Database transaction committed successfully: {TransactionId}, Duration: {Duration}ms",
                    _transaction.TransactionId, duration.TotalMilliseconds);

                await _transaction.DisposeAsync();
                _transaction = null;
                _transactionStartTime = null;
                _currentIsolationLevel = null;
                _transactionKingdomId = null;
            }
            catch (OperationCanceledException)
            {
                _logger.LogDebug("Commit transaction operation cancelled");
                await RollbackTransactionAsync(CancellationToken.None);
                throw;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error committing database transaction: {TransactionId}", _transaction?.TransactionId);
                await RollbackTransactionAsync(CancellationToken.None);
                throw new InvalidOperationException("Failed to commit database transaction", ex);
            }
        }

        /// <summary>
        /// Rolls back the current transaction and discards all changes
        /// </summary>
        public async Task RollbackTransactionAsync(CancellationToken cancellationToken = default)
        {
            try
            {
                if (_transaction == null)
                {
                    _logger.LogWarning("No active transaction to rollback");
                    return;
                }

                await _transaction.RollbackAsync(cancellationToken);

                var duration = _transactionStartTime.HasValue ? DateTime.UtcNow - _transactionStartTime.Value : TimeSpan.Zero;
                _logger.LogWarning("Database transaction rolled back: {TransactionId}, Duration: {Duration}ms",
                    _transaction.TransactionId, duration.TotalMilliseconds);

                await _transaction.DisposeAsync();
                _transaction = null;
                _transactionStartTime = null;
                _currentIsolationLevel = null;
                _transactionKingdomId = null;
            }
            catch (OperationCanceledException)
            {
                _logger.LogDebug("Rollback transaction operation cancelled");
                throw;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error rolling back database transaction: {TransactionId}", _transaction?.TransactionId);
                throw new InvalidOperationException("Failed to rollback database transaction", ex);
            }
        }

        /// <summary>
        /// Executes an operation within a transaction with automatic rollback on failure
        /// </summary>
        public async Task<TResult> ExecuteInTransactionAsync<TResult>(Func<IUnitOfWork, Task<TResult>> operation,
            IsolationLevel isolationLevel = IsolationLevel.ReadCommitted, int? kingdomId = null,
            CancellationToken cancellationToken = default)
        {
            if (operation == null)
                throw new ArgumentNullException(nameof(operation));
            if (kingdomId.HasValue && kingdomId <= 0)
                throw new ArgumentException("Kingdom ID must be positive", nameof(kingdomId));

            var transactionStartedHere = _transaction == null;

            try
            {
                if (transactionStartedHere)
                {
                    await BeginTransactionAsync(isolationLevel, kingdomId, cancellationToken);
                }

                _logger.LogDebug("Executing operation within transaction: {TransactionId}", _transaction?.TransactionId);

                var result = await operation(this);

                if (transactionStartedHere)
                {
                    await CommitTransactionAsync(cancellationToken);
                }

                _logger.LogDebug("Operation completed successfully within transaction");
                return result;
            }
            catch (OperationCanceledException)
            {
                _logger.LogDebug("Transaction operation cancelled");
                if (transactionStartedHere && _transaction != null)
                {
                    await RollbackTransactionAsync(CancellationToken.None);
                }
                throw;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error executing operation within transaction");

                if (transactionStartedHere && _transaction != null)
                {
                    await RollbackTransactionAsync(CancellationToken.None);
                }

                throw;
            }
        }

        /// <summary>
        /// Executes an operation within a transaction with automatic rollback on failure (no return value)
        /// </summary>
        public async Task ExecuteInTransactionAsync(Func<IUnitOfWork, Task> operation,
            IsolationLevel isolationLevel = IsolationLevel.ReadCommitted, int? kingdomId = null,
            CancellationToken cancellationToken = default)
        {
            await ExecuteInTransactionAsync(async (uow) =>
            {
                await operation(uow);
                return Task.CompletedTask;
            }, isolationLevel, kingdomId, cancellationToken);
        }

        /// <summary>
        /// Gets the current transaction status
        /// </summary>
        public (bool HasActiveTransaction, IsolationLevel? IsolationLevel, int? KingdomId, TimeSpan? Duration) GetTransactionStatus()
        {
            var duration = _transactionStartTime.HasValue ? DateTime.UtcNow - _transactionStartTime.Value : (TimeSpan?)null;

            return (
                HasActiveTransaction: _transaction != null,
                IsolationLevel: _currentIsolationLevel,
                KingdomId: _transactionKingdomId,
                Duration: duration
            );
        }

        #endregion

        #region Change Tracking and Persistence

        /// <summary>
        /// Saves all pending changes across all repositories
        /// </summary>
        public async Task<int> SaveChangesAsync(CancellationToken cancellationToken = default)
        {
            try
            {
                _logger.LogDebug("Saving changes across all repositories");
                var result = await _context.SaveChangesAsync(cancellationToken);
                _logger.LogDebug("Successfully saved {Count} changes", result);
                return result;
            }
            catch (OperationCanceledException)
            {
                _logger.LogDebug("Save changes operation cancelled");
                throw;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error saving changes");
                throw new InvalidOperationException("Failed to save changes", ex);
            }
        }

        /// <summary>
        /// Gets the count of pending changes across all repositories
        /// </summary>
        public Dictionary<string, (int Added, int Modified, int Deleted)> GetPendingChanges()
        {
            var pendingChanges = new Dictionary<string, (int Added, int Modified, int Deleted)>();

            var entries = _context.ChangeTracker.Entries();
            var groupedEntries = entries.GroupBy(e => e.Entity.GetType().Name);

            foreach (var group in groupedEntries)
            {
                var entityName = group.Key;
                var added = group.Count(e => e.State == EntityState.Added);
                var modified = group.Count(e => e.State == EntityState.Modified);
                var deleted = group.Count(e => e.State == EntityState.Deleted);

                if (added > 0 || modified > 0 || deleted > 0)
                {
                    pendingChanges[entityName] = (added, modified, deleted);
                }
            }

            _logger.LogDebug("Found pending changes in {EntityCount} entity types", pendingChanges.Count);
            return pendingChanges;
        }

        /// <summary>
        /// Discards all pending changes across all repositories
        /// </summary>
        public void DiscardChanges()
        {
            try
            {
                var entries = _context.ChangeTracker.Entries()
                    .Where(e => e.State != EntityState.Unchanged)
                    .ToList();

                foreach (var entry in entries)
                {
                    switch (entry.State)
                    {
                        case EntityState.Added:
                            entry.State = EntityState.Detached;
                            break;
                        case EntityState.Modified:
                            entry.Reload();
                            break;
                        case EntityState.Deleted:
                            entry.State = EntityState.Unchanged;
                            break;
                    }
                }

                _logger.LogDebug("Discarded {Count} pending changes", entries.Count);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error discarding changes");
                throw new InvalidOperationException("Failed to discard changes", ex);
            }
        }

        /// <summary>
        /// Validates all pending changes against business rules
        /// </summary>
        public async Task<(bool IsValid, Dictionary<string, string[]> ValidationErrors)> ValidatePendingChangesAsync(
            int kingdomId, CancellationToken cancellationToken = default)
        {
            try
            {
                if (kingdomId <= 0)
                    throw new ArgumentException("Kingdom ID must be positive", nameof(kingdomId));

                var validationErrors = new Dictionary<string, string[]>();
                var entries = _context.ChangeTracker.Entries()
                    .Where(e => e.State != EntityState.Unchanged)
                    .ToList();

                foreach (var entry in entries)
                {
                    var entityName = entry.Entity.GetType().Name;
                    var errors = new List<string>();

                    // Validate kingdom scoping
                    if (entry.Entity is IKingdomScoped kingdomEntity)
                    {
                        if (kingdomEntity.KingdomId != kingdomId)
                        {
                            errors.Add($"Entity belongs to kingdom {kingdomEntity.KingdomId} but operation is for kingdom {kingdomId}");
                        }
                    }

                    // Additional validation logic can be added here

                    if (errors.Any())
                    {
                        validationErrors[entityName] = errors.ToArray();
                    }
                }

                var isValid = !validationErrors.Any();
                _logger.LogDebug("Validation completed for {EntryCount} entries: {IsValid}", entries.Count, isValid ? "PASSED" : "FAILED");

                return (isValid, validationErrors);
            }
            catch (OperationCanceledException)
            {
                _logger.LogDebug("Validate pending changes operation cancelled");
                throw;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error validating pending changes for Kingdom {KingdomId}", kingdomId);
                throw new InvalidOperationException($"Failed to validate pending changes for Kingdom {kingdomId}", ex);
            }
        }

        #endregion

        #region Complex Business Operations

        /// <summary>
        /// Initializes a KvK event with all supporting data structures
        /// </summary>
        public async Task<object> InitializeKvKEventAsync(object kvkConfiguration, IEnumerable<int> participatingKingdoms,
            CancellationToken cancellationToken = default)
        {
            return await ExecuteInTransactionAsync(async (uow) =>
            {
                _logger.LogInformation("Initializing KvK event for kingdoms: {Kingdoms}", string.Join(", ", participatingKingdoms));

                // Placeholder implementation - would contain actual KvK initialization logic
                var result = new Dictionary<string, object>
                {
                    ["EventId"] = Guid.NewGuid().ToString(),
                    ["Configuration"] = kvkConfiguration,
                    ["ParticipatingKingdoms"] = participatingKingdoms.ToList(),
                    ["InitializedAt"] = DateTime.UtcNow,
                    ["Status"] = "Initialized"
                };

                await Task.CompletedTask; // Placeholder for actual implementation
                return result;
            }, cancellationToken: cancellationToken);
        }

        /// <summary>
        /// Processes a complete purchase transaction
        /// </summary>
        public async Task<object> ProcessCompletePurchaseAsync(object purchaseRequest, int playerId, int kingdomId,
            CancellationToken cancellationToken = default)
        {
            return await ExecuteInTransactionAsync(async (uow) =>
            {
                _logger.LogInformation("Processing complete purchase for Player {PlayerId} in Kingdom {KingdomId}", playerId, kingdomId);

                // Placeholder implementation - would contain actual purchase processing logic
                var result = new Dictionary<string, object>
                {
                    ["PurchaseId"] = Guid.NewGuid().ToString(),
                    ["PlayerId"] = playerId,
                    ["KingdomId"] = kingdomId,
                    ["Request"] = purchaseRequest,
                    ["ProcessedAt"] = DateTime.UtcNow,
                    ["Status"] = "Completed"
                };

                await Task.CompletedTask; // Placeholder for actual implementation
                return result;
            }, kingdomId: kingdomId, cancellationToken: cancellationToken);
        }

        /// <summary>
        /// Executes alliance merger with full data coordination
        /// </summary>
        public async Task<object> ExecuteAllianceMergerAsync(int survivingAllianceId, int mergingAllianceId,
            object mergerConfiguration, int kingdomId, CancellationToken cancellationToken = default)
        {
            return await ExecuteInTransactionAsync(async (uow) =>
            {
                _logger.LogInformation("Executing alliance merger: {MergingId} -> {SurvivingId} in Kingdom {KingdomId}",
                    mergingAllianceId, survivingAllianceId, kingdomId);

                // Placeholder implementation - would contain actual merger logic
                var result = new Dictionary<string, object>
                {
                    ["MergerId"] = Guid.NewGuid().ToString(),
                    ["SurvivingAllianceId"] = survivingAllianceId,
                    ["MergingAllianceId"] = mergingAllianceId,
                    ["Configuration"] = mergerConfiguration,
                    ["KingdomId"] = kingdomId,
                    ["ExecutedAt"] = DateTime.UtcNow,
                    ["Status"] = "Completed"
                };

                await Task.CompletedTask; // Placeholder for actual implementation
                return result;
            }, kingdomId: kingdomId, cancellationToken: cancellationToken);
        }

        /// <summary>
        /// Processes kingdom merger with comprehensive data migration
        /// </summary>
        public async Task<object> ProcessKingdomMergerAsync(int survivingKingdomId, int mergingKingdomId,
            object mergerConfiguration, CancellationToken cancellationToken = default)
        {
            return await ExecuteInTransactionAsync(async (uow) =>
            {
                _logger.LogInformation("Processing kingdom merger: {MergingId} -> {SurvivingId}",
                    mergingKingdomId, survivingKingdomId);

                // Placeholder implementation - would contain actual kingdom merger logic
                var result = new Dictionary<string, object>
                {
                    ["MergerId"] = Guid.NewGuid().ToString(),
                    ["SurvivingKingdomId"] = survivingKingdomId,
                    ["MergingKingdomId"] = mergingKingdomId,
                    ["Configuration"] = mergerConfiguration,
                    ["ExecutedAt"] = DateTime.UtcNow,
                    ["Status"] = "Completed"
                };

                await Task.CompletedTask; // Placeholder for actual implementation
                return result;
            }, cancellationToken: cancellationToken);
        }

        #endregion

        #region Performance and Monitoring

        /// <summary>
        /// Gets comprehensive performance metrics
        /// </summary>
        public async Task<object> GetPerformanceMetricsAsync(TimeSpan metricsTimeframe,
            CancellationToken cancellationToken = default)
        {
            try
            {
                if (metricsTimeframe <= TimeSpan.Zero)
                    throw new ArgumentException("Metrics timeframe must be positive", nameof(metricsTimeframe));

                _logger.LogDebug("Collecting performance metrics for timeframe: {Timeframe}", metricsTimeframe);

                var metrics = new Dictionary<string, object>
                {
                    ["CollectionTime"] = DateTime.UtcNow,
                    ["Timeframe"] = metricsTimeframe,
                    ["DatabaseMetrics"] = new
                    {
                        ActiveConnections = 1, // Placeholder
                        QueryCount = 0, // Placeholder
                        AverageResponseTime = TimeSpan.Zero // Placeholder
                    },
                    ["RepositoryMetrics"] = new
                    {
                        KingdomQueries = 0,
                        PlayerQueries = 0,
                        AllianceQueries = 0,
                        CombatQueries = 0,
                        PurchaseQueries = 0
                    }
                };

                await Task.CompletedTask; // Placeholder for actual metrics collection
                return metrics;
            }
            catch (OperationCanceledException)
            {
                _logger.LogDebug("Get performance metrics operation cancelled");
                throw;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error collecting performance metrics");
                throw new InvalidOperationException("Failed to collect performance metrics", ex);
            }
        }

        /// <summary>
        /// Validates data consistency across all repositories
        /// </summary>
        public async Task<object> ValidateDataConsistencyAsync(int? kingdomId = null, string validationScope = "standard",
            CancellationToken cancellationToken = default)
        {
            try
            {
                if (kingdomId.HasValue && kingdomId <= 0)
                    throw new ArgumentException("Kingdom ID must be positive", nameof(kingdomId));

                _logger.LogDebug("Validating data consistency: Kingdom {KingdomId}, Scope {Scope}",
                    kingdomId?.ToString() ?? "ALL", validationScope);

                var validation = new Dictionary<string, object>
                {
                    ["ValidationTime"] = DateTime.UtcNow,
                    ["KingdomId"] = kingdomId,
                    ["Scope"] = validationScope,
                    ["IsConsistent"] = true, // Placeholder
                    ["Issues"] = new List<string>(), // Placeholder
                    ["Statistics"] = new Dictionary<string, int>
                    {
                        ["TotalEntities"] = 0,
                        ["OrphanedRecords"] = 0,
                        ["ReferentialIntegrityErrors"] = 0
                    }
                };

                await Task.CompletedTask; // Placeholder for actual validation logic
                return validation;
            }
            catch (OperationCanceledException)
            {
                _logger.LogDebug("Validate data consistency operation cancelled");
                throw;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error validating data consistency");
                throw new InvalidOperationException("Failed to validate data consistency", ex);
            }
        }

        /// <summary>
        /// Optimizes database performance
        /// </summary>
        public async Task<object> OptimizeDatabasePerformanceAsync(string optimizationType = "standard",
            CancellationToken cancellationToken = default)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(optimizationType))
                    throw new ArgumentException("Optimization type cannot be empty", nameof(optimizationType));

                _logger.LogInformation("Optimizing database performance: Type {Type}", optimizationType);

                var optimization = new Dictionary<string, object>
                {
                    ["OptimizationTime"] = DateTime.UtcNow,
                    ["Type"] = optimizationType,
                    ["Results"] = new Dictionary<string, object>
                    {
                        ["IndexesRebuilt"] = 0,
                        ["StatisticsUpdated"] = 0,
                        ["TablesOptimized"] = 0,
                        ["PerformanceImprovement"] = "0%"
                    }
                };

                await Task.CompletedTask; // Placeholder for actual optimization logic
                return optimization;
            }
            catch (OperationCanceledException)
            {
                _logger.LogDebug("Database optimization operation cancelled");
                throw;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error optimizing database performance");
                throw new InvalidOperationException("Failed to optimize database performance", ex);
            }
        }

        #endregion

        #region Bulk Operations and Data Migration

        /// <summary>
        /// Executes bulk operations with transaction safety
        /// </summary>
        public async Task<TResult> ExecuteBulkOperationAsync<TResult>(Func<IUnitOfWork, int, Task<TResult>> bulkOperation,
            int batchSize = 1000, int? kingdomId = null,
            IProgress<(int Processed, int Total, string Status)>? progressCallback = null,
            CancellationToken cancellationToken = default)
        {
            if (bulkOperation == null)
                throw new ArgumentNullException(nameof(bulkOperation));
            if (batchSize <= 0)
                throw new ArgumentException("Batch size must be positive", nameof(batchSize));
            if (kingdomId.HasValue && kingdomId <= 0)
                throw new ArgumentException("Kingdom ID must be positive", nameof(kingdomId));

            return await ExecuteInTransactionAsync(async (uow) =>
            {
                _logger.LogInformation("Executing bulk operation: BatchSize {BatchSize}, Kingdom {KingdomId}",
                    batchSize, kingdomId);

                progressCallback?.Report((0, 1, "Starting bulk operation"));

                var result = await bulkOperation(uow, batchSize);

                progressCallback?.Report((1, 1, "Bulk operation completed"));
                return result;
            }, kingdomId: kingdomId, cancellationToken: cancellationToken);
        }

        /// <summary>
        /// Migrates data between kingdoms
        /// </summary>
        public async Task<object> MigrateKingdomDataAsync(int sourceKingdomId, int targetKingdomId,
            object migrationConfiguration, CancellationToken cancellationToken = default)
        {
            return await ExecuteInTransactionAsync(async (uow) =>
            {
                _logger.LogInformation("Migrating kingdom data: {SourceId} -> {TargetId}",
                    sourceKingdomId, targetKingdomId);

                var migration = new Dictionary<string, object>
                {
                    ["MigrationId"] = Guid.NewGuid().ToString(),
                    ["SourceKingdomId"] = sourceKingdomId,
                    ["TargetKingdomId"] = targetKingdomId,
                    ["Configuration"] = migrationConfiguration,
                    ["StartedAt"] = DateTime.UtcNow,
                    ["Status"] = "Completed"
                };

                await Task.CompletedTask; // Placeholder for actual migration logic
                return migration;
            }, cancellationToken: cancellationToken);
        }

        /// <summary>
        /// Creates comprehensive database backup
        /// </summary>
        public async Task<object> CreateDatabaseBackupAsync(object backupConfiguration,
            IEnumerable<int>? kingdomIds = null, CancellationToken cancellationToken = default)
        {
            try
            {
                _logger.LogInformation("Creating database backup for kingdoms: {Kingdoms}",
                    kingdomIds != null ? string.Join(", ", kingdomIds) : "ALL");

                var backup = new Dictionary<string, object>
                {
                    ["BackupId"] = Guid.NewGuid().ToString(),
                    ["Configuration"] = backupConfiguration,
                    ["KingdomIds"] = kingdomIds?.ToList(),
                    ["CreatedAt"] = DateTime.UtcNow,
                    ["Status"] = "Completed"
                };

                await Task.CompletedTask; // Placeholder for actual backup logic
                return backup;
            }
            catch (OperationCanceledException)
            {
                _logger.LogDebug("Database backup operation cancelled");
                throw;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error creating database backup");
                throw new InvalidOperationException("Failed to create database backup", ex);
            }
        }

        #endregion

        #region Kingdom-Scoped Security and Validation

        /// <summary>
        /// Validates kingdom-scoped security constraints
        /// </summary>
        public (bool IsSecure, string[] SecurityViolations, string[] Recommendations) ValidateKingdomScopedSecurity(
            int kingdomId, string operationType)
        {
            if (kingdomId <= 0)
                throw new ArgumentException("Kingdom ID must be positive", nameof(kingdomId));
            if (string.IsNullOrWhiteSpace(operationType))
                throw new ArgumentException("Operation type cannot be empty", nameof(operationType));

            _logger.LogDebug("Validating kingdom-scoped security: Kingdom {KingdomId}, Operation {OperationType}",
                kingdomId, operationType);

            var violations = new List<string>();
            var recommendations = new List<string>();

            // Placeholder security validation logic
            var isSecure = violations.Count == 0;

            return (isSecure, violations.ToArray(), recommendations.ToArray());
        }

        /// <summary>
        /// Enforces kingdom-scoped query filters
        /// </summary>
        public void EnforceKingdomQueryFilters(int kingdomId)
        {
            if (kingdomId <= 0)
                throw new ArgumentException("Kingdom ID must be positive", nameof(kingdomId));

            _logger.LogDebug("Enforcing kingdom query filters for Kingdom {KingdomId}", kingdomId);

            // Placeholder for actual query filter enforcement
        }

        /// <summary>
        /// Temporarily elevates permissions for cross-kingdom operations
        /// </summary>
        public async Task<object> ElevatePermissionsAsync(int adminId, string elevationReason,
            string operationScope, CancellationToken cancellationToken = default)
        {
            try
            {
                if (adminId <= 0)
                    throw new ArgumentException("Admin ID must be positive", nameof(adminId));
                if (string.IsNullOrWhiteSpace(elevationReason))
                    throw new ArgumentException("Elevation reason cannot be empty", nameof(elevationReason));
                if (string.IsNullOrWhiteSpace(operationScope))
                    throw new ArgumentException("Operation scope cannot be empty", nameof(operationScope));

                _logger.LogWarning("Elevating permissions for Admin {AdminId}: {Reason}", adminId, elevationReason);

                var elevationToken = new Dictionary<string, object>
                {
                    ["TokenId"] = Guid.NewGuid().ToString(),
                    ["AdminId"] = adminId,
                    ["Reason"] = elevationReason,
                    ["Scope"] = operationScope,
                    ["ElevatedAt"] = DateTime.UtcNow,
                    ["ExpiresAt"] = DateTime.UtcNow.AddHours(1) // 1 hour default
                };

                await Task.CompletedTask; // Placeholder for actual elevation logic
                return elevationToken;
            }
            catch (OperationCanceledException)
            {
                _logger.LogDebug("Elevate permissions operation cancelled");
                throw;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error elevating permissions for Admin {AdminId}", adminId);
                throw new UnauthorizedAccessException("Failed to elevate permissions", ex);
            }
        }

        /// <summary>
        /// Revokes elevated permissions
        /// </summary>
        public async Task<object> RevokeElevatedPermissionsAsync(object elevationToken, string operationSummary,
            CancellationToken cancellationToken = default)
        {
            try
            {
                if (elevationToken == null)
                    throw new ArgumentNullException(nameof(elevationToken));
                if (string.IsNullOrWhiteSpace(operationSummary))
                    throw new ArgumentException("Operation summary cannot be empty", nameof(operationSummary));

                _logger.LogInformation("Revoking elevated permissions: {Summary}", operationSummary);

                var revocation = new Dictionary<string, object>
                {
                    ["RevocationId"] = Guid.NewGuid().ToString(),
                    ["ElevationToken"] = elevationToken,
                    ["OperationSummary"] = operationSummary,
                    ["RevokedAt"] = DateTime.UtcNow
                };

                await Task.CompletedTask; // Placeholder for actual revocation logic
                return revocation;
            }
            catch (OperationCanceledException)
            {
                _logger.LogDebug("Revoke elevated permissions operation cancelled");
                throw;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error revoking elevated permissions");
                throw new InvalidOperationException("Failed to revoke elevated permissions", ex);
            }
        }

        #endregion

        #region Disposal

        /// <summary>
        /// Disposes of the UnitOfWork and all associated resources
        /// </summary>
        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        /// <summary>
        /// Protected dispose method
        /// </summary>
        protected virtual void Dispose(bool disposing)
        {
            if (!_disposed && disposing)
            {
                try
                {
                    _transaction?.Dispose();
                    _context.Dispose();
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "Error disposing UnitOfWork resources");
                }

                _disposed = true;
                _logger.LogDebug("UnitOfWork disposed successfully");
            }
        }

        /// <summary>
        /// Async disposal for cleanup of async resources
        /// </summary>
        public async ValueTask DisposeAsync()
        {
            if (!_disposed)
            {
                try
                {
                    if (_transaction != null)
                    {
                        await _transaction.DisposeAsync();
                    }

                    await _context.DisposeAsync();
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "Error disposing UnitOfWork resources asynchronously");
                }

                _disposed = true;
                _logger.LogDebug("UnitOfWork disposed asynchronously");
            }

            GC.SuppressFinalize(this);
        }

        #endregion
    }
}