/*
 * File: /src/server/ShadowedRealms.Core/Interfaces/IUnitOfWork.cs
 * Created: 2025-10-19
 * Last Modified: 2025-10-19
 * Description: Unit of Work interface providing centralized transaction management and repository coordination.
 *              Ensures data consistency across complex operations involving multiple entities and repositories.
 *              Critical for maintaining kingdom-scoped data integrity and handling complex business operations
 *              like KvK events, alliance coalitions, and purchase processing that span multiple entities.
 * Last Edit Notes: Initial implementation with comprehensive transaction management, repository coordination, and kingdom-scoped operations.
 */

using ShadowedRealms.Core.Interfaces.Repositories;
using System.Data;

namespace ShadowedRealms.Core.Interfaces
{
    /// <summary>
    /// Unit of Work interface providing centralized transaction management and repository coordination
    /// for complex operations spanning multiple entities. Ensures data consistency and kingdom-scoped
    /// security across all database operations while supporting distributed transactions and rollback scenarios.
    /// </summary>
    public interface IUnitOfWork : IDisposable
    {
        #region Repository Access Properties

        /// <summary>
        /// Gets the Kingdom repository for kingdom lifecycle, population management, KvK events, 
        /// and democratic political systems. Root repository for kingdom-scoped operations.
        /// </summary>
        IKingdomRepository Kingdoms { get; }

        /// <summary>
        /// Gets the Player repository for castle progression, troop management, resource systems,
        /// VIP mechanics, research, equipment, and all core individual gameplay features.
        /// </summary>
        IPlayerRepository Players { get; }

        /// <summary>
        /// Gets the Alliance repository for social systems, coalition mechanics, research trees,
        /// territory management, 5-tier hierarchy, and democratic leadership systems.
        /// </summary>
        IAllianceRepository Alliances { get; }

        /// <summary>
        /// Gets the Combat Log repository for field interception system, battle resolution,
        /// KvK events, stealth mechanics, dragon integration, and combat analytics.
        /// </summary>
        ICombatLogRepository CombatLogs { get; }

        /// <summary>
        /// Gets the Purchase Log repository for monetization tracking, chargeback protection,
        /// VIP progression, revenue analytics, and anti-pay-to-win balance monitoring.
        /// </summary>
        IPurchaseLogRepository PurchaseLogs { get; }

        #endregion

        #region Transaction Management

        /// <summary>
        /// Begins a new database transaction with the specified isolation level for complex operations
        /// requiring data consistency across multiple repositories. Automatically applies kingdom-scoped security.
        /// </summary>
        /// <param name="isolationLevel">The isolation level for the transaction</param>
        /// <param name="kingdomId">The kingdom context for the transaction (for security scoping)</param>
        /// <param name="cancellationToken">Cancellation token for async operation</param>
        /// <returns>Task representing the transaction initiation</returns>
        /// <exception cref="ArgumentException">Thrown when kingdomId is invalid</exception>
        /// <exception cref="InvalidOperationException">Thrown when transaction cannot be started</exception>
        /// <exception cref="OperationCanceledException">Thrown when operation is cancelled</exception>
        Task BeginTransactionAsync(IsolationLevel isolationLevel = IsolationLevel.ReadCommitted, int? kingdomId = null,
            CancellationToken cancellationToken = default);

        /// <summary>
        /// Commits the current transaction, persisting all changes made within the transaction scope.
        /// Validates kingdom-scoped security before commit and ensures data consistency across all repositories.
        /// </summary>
        /// <param name="cancellationToken">Cancellation token for async operation</param>
        /// <returns>Task representing the commit operation</returns>
        /// <exception cref="InvalidOperationException">Thrown when no active transaction or commit fails</exception>
        /// <exception cref="OperationCanceledException">Thrown when operation is cancelled</exception>
        Task CommitTransactionAsync(CancellationToken cancellationToken = default);

        /// <summary>
        /// Rolls back the current transaction, discarding all changes made within the transaction scope.
        /// Automatically triggered on exceptions or explicit rollback requests to maintain data integrity.
        /// </summary>
        /// <param name="cancellationToken">Cancellation token for async operation</param>
        /// <returns>Task representing the rollback operation</returns>
        /// <exception cref="InvalidOperationException">Thrown when no active transaction or rollback fails</exception>
        /// <exception cref="OperationCanceledException">Thrown when operation is cancelled</exception>
        Task RollbackTransactionAsync(CancellationToken cancellationToken = default);

        /// <summary>
        /// Executes an operation within a transaction scope, automatically handling commit/rollback.
        /// Provides transaction safety for complex business operations spanning multiple repositories.
        /// </summary>
        /// <typeparam name="TResult">The return type of the operation</typeparam>
        /// <param name="operation">The operation to execute within the transaction</param>
        /// <param name="isolationLevel">The isolation level for the transaction</param>
        /// <param name="kingdomId">The kingdom context for transaction security</param>
        /// <param name="cancellationToken">Cancellation token for async operation</param>
        /// <returns>The result of the operation if successful</returns>
        /// <exception cref="ArgumentNullException">Thrown when operation is null</exception>
        /// <exception cref="ArgumentException">Thrown when kingdomId is invalid</exception>
        /// <exception cref="InvalidOperationException">Thrown when transaction execution fails</exception>
        /// <exception cref="OperationCanceledException">Thrown when operation is cancelled</exception>
        Task<TResult> ExecuteInTransactionAsync<TResult>(Func<IUnitOfWork, Task<TResult>> operation,
            IsolationLevel isolationLevel = IsolationLevel.ReadCommitted, int? kingdomId = null,
            CancellationToken cancellationToken = default);

        /// <summary>
        /// Executes an operation within a transaction scope without return value, automatically handling commit/rollback.
        /// Provides transaction safety for complex business operations that don't return data.
        /// </summary>
        /// <param name="operation">The operation to execute within the transaction</param>
        /// <param name="isolationLevel">The isolation level for the transaction</param>
        /// <param name="kingdomId">The kingdom context for transaction security</param>
        /// <param name="cancellationToken">Cancellation token for async operation</param>
        /// <returns>Task representing the operation completion</returns>
        /// <exception cref="ArgumentNullException">Thrown when operation is null</exception>
        /// <exception cref="ArgumentException">Thrown when kingdomId is invalid</exception>
        /// <exception cref="InvalidOperationException">Thrown when transaction execution fails</exception>
        /// <exception cref="OperationCanceledException">Thrown when operation is cancelled</exception>
        Task ExecuteInTransactionAsync(Func<IUnitOfWork, Task> operation,
            IsolationLevel isolationLevel = IsolationLevel.ReadCommitted, int? kingdomId = null,
            CancellationToken cancellationToken = default);

        /// <summary>
        /// Gets the current transaction status including isolation level, kingdom context, and duration.
        /// Used for debugging, monitoring, and ensuring proper transaction management.
        /// </summary>
        /// <returns>Current transaction status information</returns>
        (bool HasActiveTransaction, IsolationLevel? IsolationLevel, int? KingdomId, TimeSpan? Duration) GetTransactionStatus();

        #endregion

        #region Change Tracking and Persistence

        /// <summary>
        /// Saves all pending changes across all repositories to the database without using transactions.
        /// Applies kingdom-scoped validation and maintains referential integrity across all entity changes.
        /// </summary>
        /// <param name="cancellationToken">Cancellation token for async operation</param>
        /// <returns>The number of entities successfully saved</returns>
        /// <exception cref="InvalidOperationException">Thrown when save operation fails due to validation or conflicts</exception>
        /// <exception cref="OperationCanceledException">Thrown when operation is cancelled</exception>
        Task<int> SaveChangesAsync(CancellationToken cancellationToken = default);

        /// <summary>
        /// Gets the count of pending changes across all repositories for monitoring and validation.
        /// Helps identify complex operations and potential performance impacts before committing.
        /// </summary>
        /// <returns>Count of pending changes by entity type and operation</returns>
        Dictionary<string, (int Added, int Modified, int Deleted)> GetPendingChanges();

        /// <summary>
        /// Discards all pending changes across all repositories, reverting to the last saved state.
        /// Used for cancellation scenarios and error recovery without database rollback.
        /// </summary>
        void DiscardChanges();

        /// <summary>
        /// Validates all pending changes against business rules and kingdom-scoped security before persistence.
        /// Provides early validation to prevent transaction failures and ensure data integrity.
        /// </summary>
        /// <param name="kingdomId">The kingdom context for validation</param>
        /// <param name="cancellationToken">Cancellation token for async operation</param>
        /// <returns>Validation results with details of any rule violations</returns>
        /// <exception cref="ArgumentException">Thrown when kingdomId is invalid</exception>
        /// <exception cref="OperationCanceledException">Thrown when operation is cancelled</exception>
        Task<(bool IsValid, Dictionary<string, string[]> ValidationErrors)> ValidatePendingChangesAsync(int kingdomId,
            CancellationToken cancellationToken = default);

        #endregion

        #region Complex Business Operations

        /// <summary>
        /// Executes a complete KvK event initialization spanning kingdoms, alliances, combat logs, and coalition setup.
        /// Demonstrates complex multi-repository transaction coordination with rollback safety.
        /// </summary>
        /// <param name="kvkConfiguration">Complete KvK event configuration</param>
        /// <param name="participatingKingdoms">Kingdoms participating in the event</param>
        /// <param name="cancellationToken">Cancellation token for async operation</param>
        /// <returns>Created KvK event with all supporting data structures</returns>
        /// <exception cref="ArgumentException">Thrown when configuration is invalid or kingdoms ineligible</exception>
        /// <exception cref="InvalidOperationException">Thrown when KvK initialization fails</exception>
        /// <exception cref="OperationCanceledException">Thrown when operation is cancelled</exception>
        Task<object> InitializeKvKEventAsync(object kvkConfiguration, IEnumerable<int> participatingKingdoms,
            CancellationToken cancellationToken = default);

        /// <summary>
        /// Processes a complete purchase transaction including player updates, VIP progression, purchase logging,
        /// and fraud detection across multiple repositories with full transaction safety.
        /// </summary>
        /// <param name="purchaseRequest">Complete purchase request information</param>
        /// <param name="playerId">The player making the purchase</param>
        /// <param name="kingdomId">The kingdom context for the purchase</param>
        /// <param name="cancellationToken">Cancellation token for async operation</param>
        /// <returns>Complete purchase result with all updates applied</returns>
        /// <exception cref="ArgumentException">Thrown when purchase request is invalid</exception>
        /// <exception cref="InvalidOperationException">Thrown when purchase processing fails</exception>
        /// <exception cref="OperationCanceledException">Thrown when operation is cancelled</exception>
        Task<object> ProcessCompletePurchaseAsync(object purchaseRequest, int playerId, int kingdomId,
            CancellationToken cancellationToken = default);

        /// <summary>
        /// Executes alliance merger including member transfers, research preservation, territory reassignment,
        /// and historical data consolidation across multiple entities with transaction safety.
        /// </summary>
        /// <param name="survivingAllianceId">The alliance that will continue to exist</param>
        /// <param name="mergingAllianceId">The alliance being absorbed</param>
        /// <param name="mergerConfiguration">Merger rules and member handling</param>
        /// <param name="kingdomId">The kingdom context for the merger</param>
        /// <param name="cancellationToken">Cancellation token for async operation</param>
        /// <returns>Merger result with updated alliance and member status</returns>
        /// <exception cref="ArgumentException">Thrown when merger parameters are invalid</exception>
        /// <exception cref="InvalidOperationException">Thrown when merger execution fails</exception>
        /// <exception cref="OperationCanceledException">Thrown when operation is cancelled</exception>
        Task<object> ExecuteAllianceMergerAsync(int survivingAllianceId, int mergingAllianceId,
            object mergerConfiguration, int kingdomId, CancellationToken cancellationToken = default);

        /// <summary>
        /// Processes kingdom merger including population transfers, alliance reassignments, combat history consolidation,
        /// and democratic system integration across all entity types with comprehensive transaction management.
        /// </summary>
        /// <param name="survivingKingdomId">The kingdom that will continue to exist</param>
        /// <param name="mergingKingdomId">The kingdom being absorbed</param>
        /// <param name="mergerConfiguration">Kingdom merger rules and integration settings</param>
        /// <param name="cancellationToken">Cancellation token for async operation</param>
        /// <returns>Comprehensive merger result with updated kingdom and all associated entities</returns>
        /// <exception cref="ArgumentException">Thrown when merger parameters are invalid or kingdoms incompatible</exception>
        /// <exception cref="InvalidOperationException">Thrown when kingdom merger execution fails</exception>
        /// <exception cref="OperationCanceledException">Thrown when operation is cancelled</exception>
        Task<object> ProcessKingdomMergerAsync(int survivingKingdomId, int mergingKingdomId,
            object mergerConfiguration, CancellationToken cancellationToken = default);

        #endregion

        #region Performance and Monitoring

        /// <summary>
        /// Gets comprehensive performance metrics for all repositories including query performance,
        /// transaction duration, change tracking efficiency, and kingdom-scoped operation statistics.
        /// </summary>
        /// <param name="metricsTimeframe">Time period for performance metrics collection</param>
        /// <param name="cancellationToken">Cancellation token for async operation</param>
        /// <returns>Detailed performance metrics with optimization recommendations</returns>
        /// <exception cref="ArgumentException">Thrown when timeframe is invalid</exception>
        /// <exception cref="OperationCanceledException">Thrown when operation is cancelled</exception>
        Task<object> GetPerformanceMetricsAsync(TimeSpan metricsTimeframe, CancellationToken cancellationToken = default);

        /// <summary>
        /// Validates data consistency across all repositories and entities, identifying referential integrity
        /// issues, orphaned records, and kingdom-scoped data leaks for maintenance and debugging.
        /// </summary>
        /// <param name="kingdomId">The kingdom to validate (null for global validation)</param>
        /// <param name="validationScope">Scope of validation (quick, standard, comprehensive)</param>
        /// <param name="cancellationToken">Cancellation token for async operation</param>
        /// <returns>Data consistency validation results with identified issues and repair recommendations</returns>
        /// <exception cref="ArgumentException">Thrown when parameters are invalid</exception>
        /// <exception cref="OperationCanceledException">Thrown when operation is cancelled</exception>
        Task<object> ValidateDataConsistencyAsync(int? kingdomId = null, string validationScope = "standard",
            CancellationToken cancellationToken = default);

        /// <summary>
        /// Optimizes database performance by analyzing query patterns, updating statistics, reorganizing indexes,
        /// and cleaning up fragmented data across all entity tables for improved operation efficiency.
        /// </summary>
        /// <param name="optimizationType">Type of optimization (indexes, statistics, cleanup, full)</param>
        /// <param name="cancellationToken">Cancellation token for async operation</param>
        /// <returns>Optimization results with performance improvements and recommendations</returns>
        /// <exception cref="ArgumentException">Thrown when optimization type is invalid</exception>
        /// <exception cref="InvalidOperationException">Thrown when optimization fails</exception>
        /// <exception cref="OperationCanceledException">Thrown when operation is cancelled</exception>
        Task<object> OptimizeDatabasePerformanceAsync(string optimizationType = "standard",
            CancellationToken cancellationToken = default);

        #endregion

        #region Bulk Operations and Data Migration

        /// <summary>
        /// Executes bulk operations across multiple repositories with transaction safety and progress tracking.
        /// Optimized for large-scale data operations like server mergers, mass updates, and data migrations.
        /// </summary>
        /// <typeparam name="TResult">The return type of the bulk operation</typeparam>
        /// <param name="bulkOperation">The bulk operation to execute</param>
        /// <param name="batchSize">Size of batches for processing (for memory management)</param>
        /// <param name="kingdomId">The kingdom context for bulk operations</param>
        /// <param name="progressCallback">Callback for progress reporting</param>
        /// <param name="cancellationToken">Cancellation token for async operation</param>
        /// <returns>Bulk operation result with processing statistics</returns>
        /// <exception cref="ArgumentNullException">Thrown when bulk operation is null</exception>
        /// <exception cref="ArgumentException">Thrown when parameters are invalid</exception>
        /// <exception cref="InvalidOperationException">Thrown when bulk operation fails</exception>
        /// <exception cref="OperationCanceledException">Thrown when operation is cancelled</exception>
        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);

        /// <summary>
        /// Migrates data between kingdoms during server consolidation or kingdom mergers with full referential
        /// integrity maintenance and audit trail creation for complex data transformation scenarios.
        /// </summary>
        /// <param name="sourceKingdomId">The kingdom data is being migrated from</param>
        /// <param name="targetKingdomId">The kingdom data is being migrated to</param>
        /// <param name="migrationConfiguration">Migration rules, mappings, and transformation logic</param>
        /// <param name="cancellationToken">Cancellation token for async operation</param>
        /// <returns>Migration result with transferred data statistics and audit information</returns>
        /// <exception cref="ArgumentException">Thrown when kingdom IDs are invalid or migration config is malformed</exception>
        /// <exception cref="InvalidOperationException">Thrown when data migration fails</exception>
        /// <exception cref="OperationCanceledException">Thrown when operation is cancelled</exception>
        Task<object> MigrateKingdomDataAsync(int sourceKingdomId, int targetKingdomId, object migrationConfiguration,
            CancellationToken cancellationToken = default);

        /// <summary>
        /// Creates comprehensive database backup including all kingdom data, transaction logs, and metadata
        /// with optional encryption for disaster recovery and data protection purposes.
        /// </summary>
        /// <param name="backupConfiguration">Backup settings including compression, encryption, and scope</param>
        /// <param name="kingdomIds">Specific kingdoms to backup (null for all kingdoms)</param>
        /// <param name="cancellationToken">Cancellation token for async operation</param>
        /// <returns>Backup result with file information, verification checksums, and restoration instructions</returns>
        /// <exception cref="ArgumentException">Thrown when backup configuration is invalid</exception>
        /// <exception cref="InvalidOperationException">Thrown when backup creation fails</exception>
        /// <exception cref="OperationCanceledException">Thrown when operation is cancelled</exception>
        Task<object> CreateDatabaseBackupAsync(object backupConfiguration, IEnumerable<int>? kingdomIds = null,
            CancellationToken cancellationToken = default);

        #endregion

        #region Kingdom-Scoped Security and Validation

        /// <summary>
        /// Validates that all operations within the unit of work respect kingdom boundaries and security constraints.
        /// Prevents accidental cross-kingdom data access and ensures proper security isolation.
        /// </summary>
        /// <param name="kingdomId">The kingdom context to validate against</param>
        /// <param name="operationType">The type of operation being validated</param>
        /// <returns>Security validation result with any violations identified</returns>
        /// <exception cref="ArgumentException">Thrown when kingdomId is invalid</exception>
        /// <exception cref="UnauthorizedAccessException">Thrown when security violations are detected</exception>
        (bool IsSecure, string[] SecurityViolations, string[] Recommendations) ValidateKingdomScopedSecurity(
            int kingdomId, string operationType);

        /// <summary>
        /// Enforces kingdom-scoped query filters across all repositories to prevent accidental data leakage
        /// between kingdoms. Automatically applied to all queries within the unit of work context.
        /// </summary>
        /// <param name="kingdomId">The kingdom context for query filtering</param>
        /// <exception cref="ArgumentException">Thrown when kingdomId is invalid</exception>
        /// <exception cref="InvalidOperationException">Thrown when filter enforcement fails</exception>
        void EnforceKingdomQueryFilters(int kingdomId);

        /// <summary>
        /// Temporarily elevates permissions for cross-kingdom operations requiring administrative access.
        /// Used for system maintenance, data migration, and administrative reporting with full audit logging.
        /// </summary>
        /// <param name="adminId">The administrator requesting elevated permissions</param>
        /// <param name="elevationReason">Business justification for permission elevation</param>
        /// <param name="operationScope">Scope of operations requiring elevation</param>
        /// <param name="cancellationToken">Cancellation token for async operation</param>
        /// <returns>Elevation token for authorized cross-kingdom operations</returns>
        /// <exception cref="ArgumentException">Thrown when parameters are invalid</exception>
        /// <exception cref="UnauthorizedAccessException">Thrown when admin lacks elevation authority</exception>
        /// <exception cref="OperationCanceledException">Thrown when operation is cancelled</exception>
        Task<object> ElevatePermissionsAsync(int adminId, string elevationReason, string operationScope,
            CancellationToken cancellationToken = default);

        /// <summary>
        /// Revokes elevated permissions and logs the completion of cross-kingdom operations for audit trails.
        /// Automatically called when elevation token expires or operations complete.
        /// </summary>
        /// <param name="elevationToken">The elevation token to revoke</param>
        /// <param name="operationSummary">Summary of operations performed with elevated permissions</param>
        /// <param name="cancellationToken">Cancellation token for async operation</param>
        /// <returns>Revocation result with audit log information</returns>
        /// <exception cref="ArgumentException">Thrown when elevation token is invalid</exception>
        /// <exception cref="InvalidOperationException">Thrown when permission revocation fails</exception>
        /// <exception cref="OperationCanceledException">Thrown when operation is cancelled</exception>
        Task<object> RevokeElevatedPermissionsAsync(object elevationToken, string operationSummary,
            CancellationToken cancellationToken = default);

        #endregion
    }
}