diff --git a/ShadowedRealmsMobile/src/server/ShadowedRealms.Core/Interfaces/IUnitOfWork.cs b/ShadowedRealmsMobile/src/server/ShadowedRealms.Core/Interfaces/IUnitOfWork.cs
new file mode 100644
index 0000000..49ed31b
--- /dev/null
+++ b/ShadowedRealmsMobile/src/server/ShadowedRealms.Core/Interfaces/IUnitOfWork.cs
@@ -0,0 +1,388 @@
+/*
+ * 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
+{
+ ///
+ /// 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.
+ ///
+ public interface IUnitOfWork : IDisposable
+ {
+ #region Repository Access Properties
+
+ ///
+ /// Gets the Kingdom repository for kingdom lifecycle, population management, KvK events,
+ /// and democratic political systems. Root repository for kingdom-scoped operations.
+ ///
+ IKingdomRepository Kingdoms { get; }
+
+ ///
+ /// Gets the Player repository for castle progression, troop management, resource systems,
+ /// VIP mechanics, research, equipment, and all core individual gameplay features.
+ ///
+ IPlayerRepository Players { get; }
+
+ ///
+ /// Gets the Alliance repository for social systems, coalition mechanics, research trees,
+ /// territory management, 5-tier hierarchy, and democratic leadership systems.
+ ///
+ IAllianceRepository Alliances { get; }
+
+ ///
+ /// Gets the Combat Log repository for field interception system, battle resolution,
+ /// KvK events, stealth mechanics, dragon integration, and combat analytics.
+ ///
+ ICombatLogRepository CombatLogs { get; }
+
+ ///
+ /// Gets the Purchase Log repository for monetization tracking, chargeback protection,
+ /// VIP progression, revenue analytics, and anti-pay-to-win balance monitoring.
+ ///
+ IPurchaseLogRepository PurchaseLogs { get; }
+
+ #endregion
+
+ #region Transaction Management
+
+ ///
+ /// Begins a new database transaction with the specified isolation level for complex operations
+ /// requiring data consistency across multiple repositories. Automatically applies kingdom-scoped security.
+ ///
+ /// The isolation level for the transaction
+ /// The kingdom context for the transaction (for security scoping)
+ /// Cancellation token for async operation
+ /// Task representing the transaction initiation
+ /// Thrown when kingdomId is invalid
+ /// Thrown when transaction cannot be started
+ /// Thrown when operation is cancelled
+ Task BeginTransactionAsync(IsolationLevel isolationLevel = IsolationLevel.ReadCommitted, int? kingdomId = null,
+ CancellationToken cancellationToken = default);
+
+ ///
+ /// 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.
+ ///
+ /// Cancellation token for async operation
+ /// Task representing the commit operation
+ /// Thrown when no active transaction or commit fails
+ /// Thrown when operation is cancelled
+ Task CommitTransactionAsync(CancellationToken cancellationToken = default);
+
+ ///
+ /// 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.
+ ///
+ /// Cancellation token for async operation
+ /// Task representing the rollback operation
+ /// Thrown when no active transaction or rollback fails
+ /// Thrown when operation is cancelled
+ Task RollbackTransactionAsync(CancellationToken cancellationToken = default);
+
+ ///
+ /// Executes an operation within a transaction scope, automatically handling commit/rollback.
+ /// Provides transaction safety for complex business operations spanning multiple repositories.
+ ///
+ /// The return type of the operation
+ /// The operation to execute within the transaction
+ /// The isolation level for the transaction
+ /// The kingdom context for transaction security
+ /// Cancellation token for async operation
+ /// The result of the operation if successful
+ /// Thrown when operation is null
+ /// Thrown when kingdomId is invalid
+ /// Thrown when transaction execution fails
+ /// Thrown when operation is cancelled
+ Task ExecuteInTransactionAsync(Func> operation,
+ IsolationLevel isolationLevel = IsolationLevel.ReadCommitted, int? kingdomId = null,
+ CancellationToken cancellationToken = default);
+
+ ///
+ /// 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.
+ ///
+ /// The operation to execute within the transaction
+ /// The isolation level for the transaction
+ /// The kingdom context for transaction security
+ /// Cancellation token for async operation
+ /// Task representing the operation completion
+ /// Thrown when operation is null
+ /// Thrown when kingdomId is invalid
+ /// Thrown when transaction execution fails
+ /// Thrown when operation is cancelled
+ Task ExecuteInTransactionAsync(Func operation,
+ IsolationLevel isolationLevel = IsolationLevel.ReadCommitted, int? kingdomId = null,
+ CancellationToken cancellationToken = default);
+
+ ///
+ /// Gets the current transaction status including isolation level, kingdom context, and duration.
+ /// Used for debugging, monitoring, and ensuring proper transaction management.
+ ///
+ /// Current transaction status information
+ (bool HasActiveTransaction, IsolationLevel? IsolationLevel, int? KingdomId, TimeSpan? Duration) GetTransactionStatus();
+
+ #endregion
+
+ #region Change Tracking and Persistence
+
+ ///
+ /// 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.
+ ///
+ /// Cancellation token for async operation
+ /// The number of entities successfully saved
+ /// Thrown when save operation fails due to validation or conflicts
+ /// Thrown when operation is cancelled
+ Task SaveChangesAsync(CancellationToken cancellationToken = default);
+
+ ///
+ /// Gets the count of pending changes across all repositories for monitoring and validation.
+ /// Helps identify complex operations and potential performance impacts before committing.
+ ///
+ /// Count of pending changes by entity type and operation
+ Dictionary GetPendingChanges();
+
+ ///
+ /// Discards all pending changes across all repositories, reverting to the last saved state.
+ /// Used for cancellation scenarios and error recovery without database rollback.
+ ///
+ void DiscardChanges();
+
+ ///
+ /// Validates all pending changes against business rules and kingdom-scoped security before persistence.
+ /// Provides early validation to prevent transaction failures and ensure data integrity.
+ ///
+ /// The kingdom context for validation
+ /// Cancellation token for async operation
+ /// Validation results with details of any rule violations
+ /// Thrown when kingdomId is invalid
+ /// Thrown when operation is cancelled
+ Task<(bool IsValid, Dictionary ValidationErrors)> ValidatePendingChangesAsync(int kingdomId,
+ CancellationToken cancellationToken = default);
+
+ #endregion
+
+ #region Complex Business Operations
+
+ ///
+ /// Executes a complete KvK event initialization spanning kingdoms, alliances, combat logs, and coalition setup.
+ /// Demonstrates complex multi-repository transaction coordination with rollback safety.
+ ///
+ /// Complete KvK event configuration
+ /// Kingdoms participating in the event
+ /// Cancellation token for async operation
+ /// Created KvK event with all supporting data structures
+ /// Thrown when configuration is invalid or kingdoms ineligible
+ /// Thrown when KvK initialization fails
+ /// Thrown when operation is cancelled
+ Task InitializeKvKEventAsync(object kvkConfiguration, IEnumerable participatingKingdoms,
+ CancellationToken cancellationToken = default);
+
+ ///
+ /// Processes a complete purchase transaction including player updates, VIP progression, purchase logging,
+ /// and fraud detection across multiple repositories with full transaction safety.
+ ///
+ /// Complete purchase request information
+ /// The player making the purchase
+ /// The kingdom context for the purchase
+ /// Cancellation token for async operation
+ /// Complete purchase result with all updates applied
+ /// Thrown when purchase request is invalid
+ /// Thrown when purchase processing fails
+ /// Thrown when operation is cancelled
+ Task ProcessCompletePurchaseAsync(object purchaseRequest, int playerId, int kingdomId,
+ CancellationToken cancellationToken = default);
+
+ ///
+ /// Executes alliance merger including member transfers, research preservation, territory reassignment,
+ /// and historical data consolidation across multiple entities with transaction safety.
+ ///
+ /// The alliance that will continue to exist
+ /// The alliance being absorbed
+ /// Merger rules and member handling
+ /// The kingdom context for the merger
+ /// Cancellation token for async operation
+ /// Merger result with updated alliance and member status
+ /// Thrown when merger parameters are invalid
+ /// Thrown when merger execution fails
+ /// Thrown when operation is cancelled
+ Task ExecuteAllianceMergerAsync(int survivingAllianceId, int mergingAllianceId,
+ object mergerConfiguration, int kingdomId, CancellationToken cancellationToken = default);
+
+ ///
+ /// Processes kingdom merger including population transfers, alliance reassignments, combat history consolidation,
+ /// and democratic system integration across all entity types with comprehensive transaction management.
+ ///
+ /// The kingdom that will continue to exist
+ /// The kingdom being absorbed
+ /// Kingdom merger rules and integration settings
+ /// Cancellation token for async operation
+ /// Comprehensive merger result with updated kingdom and all associated entities
+ /// Thrown when merger parameters are invalid or kingdoms incompatible
+ /// Thrown when kingdom merger execution fails
+ /// Thrown when operation is cancelled
+ Task ProcessKingdomMergerAsync(int survivingKingdomId, int mergingKingdomId,
+ object mergerConfiguration, CancellationToken cancellationToken = default);
+
+ #endregion
+
+ #region Performance and Monitoring
+
+ ///
+ /// Gets comprehensive performance metrics for all repositories including query performance,
+ /// transaction duration, change tracking efficiency, and kingdom-scoped operation statistics.
+ ///
+ /// Time period for performance metrics collection
+ /// Cancellation token for async operation
+ /// Detailed performance metrics with optimization recommendations
+ /// Thrown when timeframe is invalid
+ /// Thrown when operation is cancelled
+ Task GetPerformanceMetricsAsync(TimeSpan metricsTimeframe, CancellationToken cancellationToken = default);
+
+ ///
+ /// Validates data consistency across all repositories and entities, identifying referential integrity
+ /// issues, orphaned records, and kingdom-scoped data leaks for maintenance and debugging.
+ ///
+ /// The kingdom to validate (null for global validation)
+ /// Scope of validation (quick, standard, comprehensive)
+ /// Cancellation token for async operation
+ /// Data consistency validation results with identified issues and repair recommendations
+ /// Thrown when parameters are invalid
+ /// Thrown when operation is cancelled
+ Task ValidateDataConsistencyAsync(int? kingdomId = null, string validationScope = "standard",
+ CancellationToken cancellationToken = default);
+
+ ///
+ /// Optimizes database performance by analyzing query patterns, updating statistics, reorganizing indexes,
+ /// and cleaning up fragmented data across all entity tables for improved operation efficiency.
+ ///
+ /// Type of optimization (indexes, statistics, cleanup, full)
+ /// Cancellation token for async operation
+ /// Optimization results with performance improvements and recommendations
+ /// Thrown when optimization type is invalid
+ /// Thrown when optimization fails
+ /// Thrown when operation is cancelled
+ Task OptimizeDatabasePerformanceAsync(string optimizationType = "standard",
+ CancellationToken cancellationToken = default);
+
+ #endregion
+
+ #region Bulk Operations and Data Migration
+
+ ///
+ /// 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.
+ ///
+ /// The return type of the bulk operation
+ /// The bulk operation to execute
+ /// Size of batches for processing (for memory management)
+ /// The kingdom context for bulk operations
+ /// Callback for progress reporting
+ /// Cancellation token for async operation
+ /// Bulk operation result with processing statistics
+ /// Thrown when bulk operation is null
+ /// Thrown when parameters are invalid
+ /// Thrown when bulk operation fails
+ /// Thrown when operation is cancelled
+ Task ExecuteBulkOperationAsync(Func> bulkOperation,
+ int batchSize = 1000, int? kingdomId = null, IProgress<(int Processed, int Total, string Status)>? progressCallback = null,
+ CancellationToken cancellationToken = default);
+
+ ///
+ /// Migrates data between kingdoms during server consolidation or kingdom mergers with full referential
+ /// integrity maintenance and audit trail creation for complex data transformation scenarios.
+ ///
+ /// The kingdom data is being migrated from
+ /// The kingdom data is being migrated to
+ /// Migration rules, mappings, and transformation logic
+ /// Cancellation token for async operation
+ /// Migration result with transferred data statistics and audit information
+ /// Thrown when kingdom IDs are invalid or migration config is malformed
+ /// Thrown when data migration fails
+ /// Thrown when operation is cancelled
+ Task MigrateKingdomDataAsync(int sourceKingdomId, int targetKingdomId, object migrationConfiguration,
+ CancellationToken cancellationToken = default);
+
+ ///
+ /// Creates comprehensive database backup including all kingdom data, transaction logs, and metadata
+ /// with optional encryption for disaster recovery and data protection purposes.
+ ///
+ /// Backup settings including compression, encryption, and scope
+ /// Specific kingdoms to backup (null for all kingdoms)
+ /// Cancellation token for async operation
+ /// Backup result with file information, verification checksums, and restoration instructions
+ /// Thrown when backup configuration is invalid
+ /// Thrown when backup creation fails
+ /// Thrown when operation is cancelled
+ Task CreateDatabaseBackupAsync(object backupConfiguration, IEnumerable? kingdomIds = null,
+ CancellationToken cancellationToken = default);
+
+ #endregion
+
+ #region Kingdom-Scoped Security and Validation
+
+ ///
+ /// 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.
+ ///
+ /// The kingdom context to validate against
+ /// The type of operation being validated
+ /// Security validation result with any violations identified
+ /// Thrown when kingdomId is invalid
+ /// Thrown when security violations are detected
+ (bool IsSecure, string[] SecurityViolations, string[] Recommendations) ValidateKingdomScopedSecurity(
+ int kingdomId, string operationType);
+
+ ///
+ /// 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.
+ ///
+ /// The kingdom context for query filtering
+ /// Thrown when kingdomId is invalid
+ /// Thrown when filter enforcement fails
+ void EnforceKingdomQueryFilters(int kingdomId);
+
+ ///
+ /// Temporarily elevates permissions for cross-kingdom operations requiring administrative access.
+ /// Used for system maintenance, data migration, and administrative reporting with full audit logging.
+ ///
+ /// The administrator requesting elevated permissions
+ /// Business justification for permission elevation
+ /// Scope of operations requiring elevation
+ /// Cancellation token for async operation
+ /// Elevation token for authorized cross-kingdom operations
+ /// Thrown when parameters are invalid
+ /// Thrown when admin lacks elevation authority
+ /// Thrown when operation is cancelled
+ Task ElevatePermissionsAsync(int adminId, string elevationReason, string operationScope,
+ CancellationToken cancellationToken = default);
+
+ ///
+ /// Revokes elevated permissions and logs the completion of cross-kingdom operations for audit trails.
+ /// Automatically called when elevation token expires or operations complete.
+ ///
+ /// The elevation token to revoke
+ /// Summary of operations performed with elevated permissions
+ /// Cancellation token for async operation
+ /// Revocation result with audit log information
+ /// Thrown when elevation token is invalid
+ /// Thrown when permission revocation fails
+ /// Thrown when operation is cancelled
+ Task RevokeElevatedPermissionsAsync(object elevationToken, string operationSummary,
+ CancellationToken cancellationToken = default);
+
+ #endregion
+ }
+}
\ No newline at end of file
diff --git a/ShadowedRealmsMobile/src/server/ShadowedRealms.Core/Interfaces/Repositories/IAllianceRepository.cs b/ShadowedRealmsMobile/src/server/ShadowedRealms.Core/Interfaces/Repositories/IAllianceRepository.cs
new file mode 100644
index 0000000..916e72f
--- /dev/null
+++ b/ShadowedRealmsMobile/src/server/ShadowedRealms.Core/Interfaces/Repositories/IAllianceRepository.cs
@@ -0,0 +1,592 @@
+/*
+ * File: /src/server/ShadowedRealms.Core/Interfaces/Repositories/IAllianceRepository.cs
+ * Created: 2025-10-19
+ * Last Modified: 2025-10-19
+ * Description: Alliance repository interface defining alliance-specific data access operations.
+ * Handles alliance lifecycle, coalition systems, research trees, territory management,
+ * 5-tier hierarchy, member management, and democratic leadership systems. Core innovation
+ * is the coalition system that preserves alliance identity during KvK events.
+ * Last Edit Notes: Initial implementation with coalition mechanics, research trees, territory systems, and democratic leadership.
+ */
+
+using ShadowedRealms.Core.Models;
+using ShadowedRealms.Core.Models.Alliance;
+using System.Linq.Expressions;
+
+namespace ShadowedRealms.Core.Interfaces.Repositories
+{
+ ///
+ /// Repository interface for Alliance entity operations, providing comprehensive alliance lifecycle management,
+ /// coalition systems, research trees, territory control, democratic leadership, and member coordination.
+ /// Core innovation: Coalition system preserves alliance independence during kingdom events.
+ ///
+ public interface IAllianceRepository : IRepository
+ {
+ #region Alliance Lifecycle Management
+
+ ///
+ /// Creates a new alliance within the specified kingdom with initial configuration and founder assignment.
+ /// Automatically sets up 5-tier leadership hierarchy, research trees, and territory management systems.
+ ///
+ /// The name for the new alliance (must be unique within kingdom)
+ /// Short alliance tag (2-5 characters, unique within kingdom)
+ /// The player who will become the alliance leader
+ /// The kingdom where the alliance will be created
+ /// Initial alliance setup and policies
+ /// Cancellation token for async operation
+ /// The newly created alliance with founder assigned as leader
+ /// Thrown when name/tag is invalid, taken, or founder is ineligible
+ /// Thrown when alliance creation fails due to system constraints
+ /// Thrown when operation is cancelled
+ Task CreateNewAllianceAsync(string allianceName, string allianceTag, int founderId, int kingdomId,
+ object foundingConfiguration, CancellationToken cancellationToken = default);
+
+ ///
+ /// Gets an alliance by its unique tag within the specified kingdom context.
+ /// Used for alliance lookup, invitation systems, and diplomatic communications.
+ ///
+ /// The alliance tag to search for
+ /// The kingdom context for the search
+ /// Cancellation token for async operation
+ /// The alliance if found within the kingdom, null otherwise
+ /// Thrown when allianceTag is null/empty or kingdomId is invalid
+ /// Thrown when operation is cancelled
+ Task GetAllianceByTagAsync(string allianceTag, int kingdomId,
+ CancellationToken cancellationToken = default);
+
+ ///
+ /// Disbands an alliance, handling member redistribution, resource transfers, and historical data preservation.
+ /// Manages coalition withdrawals, territory releases, and research tree preservation for members.
+ ///
+ /// The alliance to disband
+ /// The kingdom context for the operation
+ /// Reason for disbanding (for historical records)
+ /// The leader authorizing the disbandment
+ /// Cancellation token for async operation
+ /// True if alliance was successfully disbanded
+ /// Thrown when parameters are invalid or player lacks authority
+ /// Thrown when alliance cannot be disbanded due to active commitments
+ /// Thrown when operation is cancelled
+ Task DisbandAllianceAsync(int allianceId, int kingdomId, string disbandReason, int authorizingPlayerId,
+ CancellationToken cancellationToken = default);
+
+ ///
+ /// Archives an inactive alliance while preserving historical data and member contribution records.
+ /// Used for alliances that no longer have active leadership or sufficient membership.
+ ///
+ /// The alliance to archive
+ /// The kingdom context for the operation
+ /// Reason for archiving (inactivity, merger, etc.)
+ /// Cancellation token for async operation
+ /// True if alliance was archived successfully
+ /// Thrown when parameters are invalid
+ /// Thrown when alliance has active members or commitments
+ /// Thrown when operation is cancelled
+ Task ArchiveAllianceAsync(int allianceId, int kingdomId, string archiveReason,
+ CancellationToken cancellationToken = default);
+
+ #endregion
+
+ #region Coalition System (Core Innovation)
+
+ ///
+ /// Creates a coalition between multiple alliances for KvK events while preserving individual alliance identities.
+ /// CORE INNOVATION: Allows cross-alliance cooperation without forced merging or identity loss.
+ ///
+ /// Alliances joining the coalition
+ /// Name for the temporary coalition
+ /// Type of event requiring coalition (KvK, territory war, etc.)
+ /// The kingdom context for the operation
+ /// Coalition leadership structure and resource sharing rules
+ /// Cancellation token for async operation
+ /// The created coalition with participating alliances
+ /// Thrown when parameters are invalid or alliances are ineligible
+ /// Thrown when coalition creation fails due to conflicts
+ /// Thrown when operation is cancelled
+ Task CreateCoalitionAsync(IEnumerable participatingAllianceIds, string coalitionName,
+ string eventType, int kingdomId, object coalitionConfiguration, CancellationToken cancellationToken = default);
+
+ ///
+ /// Gets alliances that are eligible for coalition participation based on compatibility metrics,
+ /// leadership activity, member engagement, and strategic alignment assessment.
+ ///
+ /// The alliance seeking coalition partners
+ /// The type of event requiring coalition
+ /// The kingdom context for the search
+ /// Cancellation token for async operation
+ /// Compatible alliances with compatibility scores and synergy analysis
+ /// Thrown when parameters are invalid
+ /// Thrown when operation is cancelled
+ Task> GetCoalitionEligibleAlliancesAsync(
+ int initiatingAllianceId, string eventType, int kingdomId, CancellationToken cancellationToken = default);
+
+ ///
+ /// Updates coalition participation status for an alliance, handling role assignments, resource contributions,
+ /// and coordination responsibilities while maintaining alliance independence.
+ ///
+ /// The alliance updating coalition status
+ /// The coalition being joined or left (null to leave all coalitions)
+ /// Role within the coalition (coordinator, support, specialist, etc.)
+ /// The kingdom context for the operation
+ /// Cancellation token for async operation
+ /// Updated alliance with new coalition status
+ /// Thrown when parameters are invalid or role assignment fails
+ /// Thrown when coalition change violates agreements
+ /// Thrown when operation is cancelled
+ Task UpdateCoalitionParticipationAsync(int allianceId, int? coalitionId, string? participationRole,
+ int kingdomId, CancellationToken cancellationToken = default);
+
+ ///
+ /// Gets coalition performance metrics for participating alliances including contribution levels,
+ /// coordination effectiveness, and individual alliance achievements within coalition context.
+ ///
+ /// The coalition to analyze
+ /// The kingdom context for the operation
+ /// Cancellation token for async operation
+ /// Coalition performance breakdown by participating alliance
+ /// Thrown when parameters are invalid
+ /// Thrown when operation is cancelled
+ Task GetCoalitionPerformanceMetricsAsync(int coalitionId, int kingdomId,
+ CancellationToken cancellationToken = default);
+
+ ///
+ /// Dissolves a coalition while preserving individual alliance achievements and returning control
+ /// to individual alliance leadership. Handles resource redistribution and historical record keeping.
+ ///
+ /// The coalition to dissolve
+ /// The kingdom context for the operation
+ /// Reason for coalition dissolution
+ /// Cancellation token for async operation
+ /// Updated participating alliances with individual control restored
+ /// Thrown when parameters are invalid
+ /// Thrown when coalition cannot be dissolved due to active commitments
+ /// Thrown when operation is cancelled
+ Task> DissolveCoalitionAsync(int coalitionId, int kingdomId, string dissolutionReason,
+ CancellationToken cancellationToken = default);
+
+ #endregion
+
+ #region Research Tree System
+
+ ///
+ /// Updates alliance research progress in specific technology areas, validating prerequisites,
+ /// resource costs, and member contribution requirements. Handles Military, Economic, and Technology branches.
+ ///
+ /// The alliance conducting research
+ /// The research area being advanced (Military, Economic, Technology)
+ /// The target research level
+ /// Members contributing resources to the research
+ /// The kingdom context for the operation
+ /// Cancellation token for async operation
+ /// Updated alliance with new research level and unlocked bonuses
+ /// Thrown when parameters are invalid or research violates prerequisites
+ /// Thrown when alliance lacks resources or member contributions
+ /// Thrown when operation is cancelled
+ Task UpdateAllianceResearchAsync(int allianceId, string researchArea, int researchLevel,
+ Dictionary contributingMembers, int kingdomId, CancellationToken cancellationToken = default);
+
+ ///
+ /// Gets alliances by research specialization for coalition formation, diplomatic relations,
+ /// and strategic partnership identification. Matches alliances with complementary research focuses.
+ ///
+ /// The kingdom to search within
+ /// Minimum research levels in specific areas
+ /// Cancellation token for async operation
+ /// Alliances meeting the research specialization criteria
+ /// Thrown when parameters are invalid
+ /// Thrown when operation is cancelled
+ Task> GetAlliancesByResearchSpecializationAsync(int kingdomId,
+ Dictionary researchCriteria, CancellationToken cancellationToken = default);
+
+ ///
+ /// Calculates total research bonuses available to alliance members including base alliance research,
+ /// coalition bonuses, and member contribution rewards. Used for individual player bonus calculations.
+ ///
+ /// The alliance to calculate bonuses for
+ /// The kingdom context for the operation
+ /// Whether to include bonuses from coalition participation
+ /// Cancellation token for async operation
+ /// Comprehensive breakdown of all research bonuses available to members
+ /// Thrown when parameters are invalid
+ /// Thrown when operation is cancelled
+ Task CalculateAllianceResearchBonusesAsync(int allianceId, int kingdomId, bool includeCoalitionBonuses = true,
+ CancellationToken cancellationToken = default);
+
+ ///
+ /// Records member contributions to alliance research including resources, time, and expertise.
+ /// Tracks individual contribution metrics for reward distribution and leadership evaluation.
+ ///
+ /// The alliance receiving contributions
+ /// The member making the contribution
+ /// Resources, time, or expertise contributed
+ /// The kingdom context for the operation
+ /// Cancellation token for async operation
+ /// Updated alliance with recorded contribution and member recognition
+ /// Thrown when parameters are invalid or member is not in alliance
+ /// Thrown when contribution cannot be processed
+ /// Thrown when operation is cancelled
+ Task RecordResearchContributionAsync(int allianceId, int memberId, object contributionDetails,
+ int kingdomId, CancellationToken cancellationToken = default);
+
+ #endregion
+
+ #region Territory Management
+
+ ///
+ /// Claims territory for an alliance, validating adjacency requirements, resource costs, and capacity limits.
+ /// Handles contested zones, proximity to other alliances, and strategic resource locations.
+ ///
+ /// The alliance claiming territory
+ /// The coordinates of the territory to claim
+ /// Type of territory (standard, resource, strategic)
+ /// The kingdom context for the operation
+ /// Cancellation token for async operation
+ /// Updated alliance with new territory claim
+ /// Thrown when parameters are invalid or territory cannot be claimed
+ /// Thrown when alliance lacks requirements for territory claim
+ /// Thrown when operation is cancelled
+ Task ClaimTerritoryAsync(int allianceId, (int X, int Y) territoryCoordinates, string territoryType,
+ int kingdomId, CancellationToken cancellationToken = default);
+
+ ///
+ /// Upgrades alliance territory buildings including resource generation facilities, defensive structures,
+ /// and member benefit buildings. Validates construction prerequisites and resource costs.
+ ///
+ /// The alliance upgrading territory
+ /// The specific territory being upgraded
+ /// Dictionary of building types and target levels
+ /// The kingdom context for the operation
+ /// Cancellation token for async operation
+ /// Updated alliance with upgraded territory buildings
+ /// Thrown when parameters are invalid or upgrades violate rules
+ /// Thrown when alliance lacks resources for upgrades
+ /// Thrown when operation is cancelled
+ Task UpgradeTerritoryBuildingsAsync(int allianceId, int territoryId, Dictionary buildingUpgrades,
+ int kingdomId, CancellationToken cancellationToken = default);
+
+ ///
+ /// Gets alliances with territory in contested zones around strategic forest areas and resource locations.
+ /// Used for KvK planning, territorial conflicts, and strategic resource competition analysis.
+ ///
+ /// The contested zone to analyze
+ /// The kingdom context for the search
+ /// Cancellation token for async operation
+ /// Alliances with territorial claims in the contested zone
+ /// Thrown when parameters are invalid
+ /// Thrown when operation is cancelled
+ Task> GetAlliancesInContestedZoneAsync(
+ (int X, int Y) contestedZoneCoordinates, int kingdomId, CancellationToken cancellationToken = default);
+
+ ///
+ /// Calculates territory control bonuses for alliance members including resource generation,
+ /// defensive advantages, and strategic positioning benefits.
+ ///
+ /// The alliance to calculate bonuses for
+ /// The kingdom context for the operation
+ /// Cancellation token for async operation
+ /// Comprehensive territory bonus breakdown for alliance members
+ /// Thrown when parameters are invalid
+ /// Thrown when operation is cancelled
+ Task CalculateTerritoryBonusesAsync(int allianceId, int kingdomId,
+ CancellationToken cancellationToken = default);
+
+ ///
+ /// Releases alliance territory claims, handling resource redistribution and member notification.
+ /// Can be voluntary (strategic repositioning) or forced (insufficient maintenance/defense).
+ ///
+ /// The alliance releasing territory
+ /// Specific territories to release (empty for all territory)
+ /// Reason for territory release
+ /// The kingdom context for the operation
+ /// Cancellation token for async operation
+ /// Updated alliance with released territories
+ /// Thrown when parameters are invalid
+ /// Thrown when territory release fails due to active conflicts
+ /// Thrown when operation is cancelled
+ Task ReleaseTerritoryAsync(int allianceId, IEnumerable? territoryIds, string releaseReason,
+ int kingdomId, CancellationToken cancellationToken = default);
+
+ #endregion
+
+ #region 5-Tier Leadership Hierarchy
+
+ ///
+ /// Updates alliance leadership structure using the 5-tier hierarchy system with role-based permissions.
+ /// Handles Leader, Co-Leaders, Generals, Captains, and Members with appropriate authority delegation.
+ ///
+ /// The alliance updating leadership
+ /// Dictionary of member IDs and new roles
+ /// The current leader authorizing changes
+ /// The kingdom context for the operation
+ /// Cancellation token for async operation
+ /// Updated alliance with new leadership structure
+ /// Thrown when parameters are invalid or player lacks authority
+ /// Thrown when leadership changes violate hierarchy rules
+ /// Thrown when operation is cancelled
+ Task UpdateLeadershipHierarchyAsync(int allianceId, Dictionary leadershipChanges,
+ int authorizingPlayerId, int kingdomId, CancellationToken cancellationToken = default);
+
+ ///
+ /// Gets alliance leadership structure with role assignments, permissions, and activity status.
+ /// Provides complete hierarchy visualization for member management and authority tracking.
+ ///
+ /// The alliance to get leadership for
+ /// The kingdom context for the operation
+ /// Cancellation token for async operation
+ /// Complete leadership hierarchy with roles and permissions
+ /// Thrown when parameters are invalid
+ /// Thrown when operation is cancelled
+ Task GetAllianceLeadershipAsync(int allianceId, int kingdomId,
+ CancellationToken cancellationToken = default);
+
+ ///
+ /// Validates leadership action permissions based on role hierarchy and specific operation requirements.
+ /// Prevents unauthorized actions while supporting delegated authority within the alliance structure.
+ ///
+ /// The alliance context for validation
+ /// The player attempting the action
+ /// The type of action being attempted
+ /// The kingdom context for validation
+ /// Cancellation token for async operation
+ /// Permission validation result with authority level and restrictions
+ /// Thrown when parameters are invalid
+ /// Thrown when operation is cancelled
+ Task<(bool IsAuthorized, string AuthorityLevel, string[] Restrictions)> ValidateLeadershipActionAsync(
+ int allianceId, int playerId, string actionType, int kingdomId, CancellationToken cancellationToken = default);
+
+ ///
+ /// Initiates democratic leadership transition within the alliance, setting up voting systems
+ /// and succession planning for leadership changes and emergency leadership transfer.
+ ///
+ /// The alliance conducting leadership transition
+ /// Type of transition (election, succession, emergency)
+ /// Eligible candidates for leadership positions
+ /// The kingdom context for the operation
+ /// Cancellation token for async operation
+ /// Leadership transition configuration with voting setup
+ /// Thrown when parameters are invalid or candidates are ineligible
+ /// Thrown when transition cannot be initiated
+ /// Thrown when operation is cancelled
+ Task InitiateLeadershipTransitionAsync(int allianceId, string transitionType, IEnumerable candidateIds,
+ int kingdomId, CancellationToken cancellationToken = default);
+
+ #endregion
+
+ #region Member Management
+
+ ///
+ /// Processes member applications to join the alliance, validating eligibility requirements,
+ /// cooldown periods, and alliance capacity limits. Handles both applications and invitations.
+ ///
+ /// The alliance receiving the application
+ /// The player applying to join
+ /// Application or invitation
+ /// The kingdom context for the operation
+ /// Member sponsoring the application (if applicable)
+ /// Cancellation token for async operation
+ /// Application result with status and next steps
+ /// Thrown when parameters are invalid or applicant is ineligible
+ /// Thrown when application cannot be processed
+ /// Thrown when operation is cancelled
+ Task ProcessMemberApplicationAsync(int allianceId, int applicantId, string applicationMethod,
+ int kingdomId, int? sponsoringMemberId = null, CancellationToken cancellationToken = default);
+
+ ///
+ /// Removes a member from the alliance, handling voluntary departures, kicks, and disciplinary actions.
+ /// Manages resource contribution settlements, role transitions, and exit procedures.
+ ///
+ /// The alliance losing the member
+ /// The member being removed
+ /// Voluntary departure, kick, or disciplinary action
+ /// The leader authorizing the removal (for kicks)
+ /// The kingdom context for the operation
+ /// Reason for removal (for record keeping)
+ /// Cancellation token for async operation
+ /// Updated alliance with member removed and resources settled
+ /// Thrown when parameters are invalid or player lacks authority
+ /// Thrown when member removal violates alliance policies
+ /// Thrown when operation is cancelled
+ Task RemoveMemberAsync(int allianceId, int memberId, string removalType, int kingdomId,
+ int? authorizingPlayerId = null, string? removalReason = null, CancellationToken cancellationToken = default);
+
+ ///
+ /// Updates member contribution tracking including research donations, territory support,
+ /// military assistance, and social engagement metrics for recognition and reward systems.
+ ///
+ /// The alliance tracking contributions
+ /// The member making contributions
+ /// Detailed contribution information
+ /// The kingdom context for the operation
+ /// Cancellation token for async operation
+ /// Updated alliance with recorded member contributions
+ /// Thrown when parameters are invalid or member is not in alliance
+ /// Thrown when contribution tracking fails
+ /// Thrown when operation is cancelled
+ Task UpdateMemberContributionsAsync(int allianceId, int memberId, object contributionData,
+ int kingdomId, CancellationToken cancellationToken = default);
+
+ ///
+ /// Gets member performance analytics for alliance management including activity levels,
+ /// contribution history, leadership potential, and social engagement metrics.
+ ///
+ /// The alliance to analyze members for
+ /// Type of analysis (performance, potential, engagement)
+ /// The kingdom context for the operation
+ /// Cancellation token for async operation
+ /// Member analytics with performance rankings and development recommendations
+ /// Thrown when parameters are invalid
+ /// Thrown when operation is cancelled
+ Task GetMemberPerformanceAnalyticsAsync(int allianceId, string analysisType, int kingdomId,
+ CancellationToken cancellationToken = default);
+
+ #endregion
+
+ #region Resource and Economic Management
+
+ ///
+ /// Manages alliance treasury including member contributions, resource allocation, and emergency reserves.
+ /// Handles collective resource pooling for research, territory maintenance, and member assistance.
+ ///
+ /// The alliance managing treasury
+ /// Resource deposits, withdrawals, or allocations
+ /// The leader authorizing the transaction
+ /// The kingdom context for the operation
+ /// Cancellation token for async operation
+ /// Updated alliance with new treasury status
+ /// Thrown when parameters are invalid or player lacks authority
+ /// Thrown when treasury transaction violates policies
+ /// Thrown when operation is cancelled
+ Task ManageAllianceTreasuryAsync(int allianceId, object treasuryTransaction, int authorizingPlayerId,
+ int kingdomId, CancellationToken cancellationToken = default);
+
+ ///
+ /// Facilitates resource sharing between alliance members including loans, gifts, and emergency assistance.
+ /// Tracks member-to-member resource transfers and alliance-sponsored support programs.
+ ///
+ /// The alliance facilitating resource sharing
+ /// The member providing resources
+ /// The member receiving resources
+ /// Resources being transferred
+ /// Gift, loan, or emergency assistance
+ /// The kingdom context for the operation
+ /// Cancellation token for async operation
+ /// Updated alliance with recorded resource transfer
+ /// Thrown when parameters are invalid or members are ineligible
+ /// Thrown when resource transfer violates policies
+ /// Thrown when operation is cancelled
+ Task FacilitateResourceSharingAsync(int allianceId, int senderId, int recipientId,
+ object resourceTransfer, string transferType, int kingdomId, CancellationToken cancellationToken = default);
+
+ ///
+ /// Gets alliance economic analytics including resource generation efficiency, member contribution patterns,
+ /// treasury health, and economic competitiveness compared to other alliances.
+ ///
+ /// The alliance to analyze
+ /// Time period for economic analysis
+ /// The kingdom context for the operation
+ /// Cancellation token for async operation
+ /// Comprehensive economic analysis with trends and recommendations
+ /// Thrown when parameters are invalid
+ /// Thrown when operation is cancelled
+ Task GetAllianceEconomicAnalyticsAsync(int allianceId, TimeSpan analysisTimeframe, int kingdomId,
+ CancellationToken cancellationToken = default);
+
+ #endregion
+
+ #region Alliance Analytics and Performance
+
+ ///
+ /// Gets comprehensive alliance performance metrics including member satisfaction, military effectiveness,
+ /// economic efficiency, territorial control, and social engagement for leadership analysis.
+ ///
+ /// The alliance to analyze
+ /// The kingdom context for the operation
+ /// Surface-level, detailed, or comprehensive analysis
+ /// Cancellation token for async operation
+ /// Detailed alliance performance analytics with actionable insights
+ /// Thrown when parameters are invalid
+ /// Thrown when operation is cancelled
+ Task GetAlliancePerformanceMetricsAsync(int allianceId, int kingdomId, string analysisDepth = "detailed",
+ CancellationToken cancellationToken = default);
+
+ ///
+ /// Gets alliance ranking and competitive position within the kingdom including power rankings,
+ /// territorial control, research advancement, and member satisfaction benchmarks.
+ ///
+ /// The kingdom to generate rankings for
+ /// The metric to rank by (power, territory, research, satisfaction)
+ /// Number of top alliances to return
+ /// Cancellation token for async operation
+ /// Alliance rankings with detailed competitive analysis
+ /// Thrown when parameters are invalid
+ /// Thrown when operation is cancelled
+ Task> GetAllianceRankingsAsync(
+ int kingdomId, string rankingCategory, int topCount = 50, CancellationToken cancellationToken = default);
+
+ ///
+ /// Generates alliance health report identifying potential issues like leadership conflicts,
+ /// member dissatisfaction, resource shortages, or strategic vulnerabilities requiring attention.
+ ///
+ /// The alliance to assess
+ /// The kingdom context for the operation
+ /// Cancellation token for async operation
+ /// Alliance health assessment with priority action items
+ /// Thrown when parameters are invalid
+ /// Thrown when operation is cancelled
+ Task GenerateAllianceHealthReportAsync(int allianceId, int kingdomId,
+ CancellationToken cancellationToken = default);
+
+ #endregion
+
+ #region Democratic Host Selection for KvK
+
+ ///
+ /// Initiates democratic host selection process for KvK events where alliance members vote
+ /// for leadership roles during kingdom events. Ensures fair representation and member engagement.
+ ///
+ /// The alliance participating in host selection
+ /// The KvK event requiring host selection
+ /// Leadership roles available during the event
+ /// The kingdom context for the operation
+ /// Cancellation token for async operation
+ /// Host selection voting configuration with candidate nominations
+ /// Thrown when parameters are invalid or alliance not eligible
+ /// Thrown when host selection cannot be initiated
+ /// Thrown when operation is cancelled
+ Task InitiateKvKHostSelectionAsync(int allianceId, int kvkEventId, IEnumerable availableRoles,
+ int kingdomId, CancellationToken cancellationToken = default);
+
+ ///
+ /// Processes votes for alliance representatives in KvK host selection, ensuring democratic
+ /// participation and transparent selection of alliance members for kingdom leadership roles.
+ ///
+ /// The alliance conducting voting
+ /// The member casting their vote
+ /// Vote selections for available roles
+ /// The kingdom context for the operation
+ /// Cancellation token for async operation
+ /// Updated voting status with member participation tracking
+ /// Thrown when parameters are invalid or member ineligible to vote
+ /// Thrown when voting fails due to timing or eligibility
+ /// Thrown when operation is cancelled
+ Task ProcessKvKHostVoteAsync(int allianceId, int votingMemberId, object voteConfiguration,
+ int kingdomId, CancellationToken cancellationToken = default);
+
+ ///
+ /// Finalizes KvK host selection results, appointing alliance representatives to kingdom roles
+ /// and establishing authority delegation for the duration of the KvK event.
+ ///
+ /// The alliance finalizing host selection
+ /// Voting results and selected representatives
+ /// The kingdom context for the operation
+ /// Cancellation token for async operation
+ /// Updated alliance with appointed KvK representatives and authority delegation
+ /// Thrown when parameters are invalid or results are contested
+ /// Thrown when host selection finalization fails
+ /// Thrown when operation is cancelled
+ Task FinalizeKvKHostSelectionAsync(int allianceId, object selectionResults, int kingdomId,
+ CancellationToken cancellationToken = default);
+
+ #endregion
+ }
+}
\ No newline at end of file
diff --git a/ShadowedRealmsMobile/src/server/ShadowedRealms.Core/Interfaces/Repositories/ICombatLogRepository.cs b/ShadowedRealmsMobile/src/server/ShadowedRealms.Core/Interfaces/Repositories/ICombatLogRepository.cs
new file mode 100644
index 0000000..567529a
--- /dev/null
+++ b/ShadowedRealmsMobile/src/server/ShadowedRealms.Core/Interfaces/Repositories/ICombatLogRepository.cs
@@ -0,0 +1,522 @@
+/*
+ * File: /src/server/ShadowedRealms.Core/Interfaces/Repositories/ICombatLogRepository.cs
+ * Created: 2025-10-19
+ * Last Modified: 2025-10-19
+ * Description: Combat log repository interface defining combat-specific data access operations.
+ * Handles field interception combat, battle resolution, KvK events, stealth mechanics,
+ * dragon integration, speed limitations, and attack classifications. Core innovation
+ * is the field interception system where defenders can meet attackers before they reach castles.
+ * Last Edit Notes: Initial implementation with field interception, battle resolution, KvK mechanics, and combat analytics.
+ */
+
+using ShadowedRealms.Core.Models;
+using ShadowedRealms.Core.Models.Combat;
+using System.Linq.Expressions;
+
+namespace ShadowedRealms.Core.Interfaces.Repositories
+{
+ ///
+ /// Repository interface for CombatLog entity operations, providing comprehensive combat system management,
+ /// field interception mechanics, battle resolution, KvK event tracking, and combat analytics.
+ /// Core innovation: Field interception system allows defenders to meet attackers before castle sieges.
+ ///
+ public interface ICombatLogRepository : IRepository
+ {
+ #region Field Interception System (Core Innovation)
+
+ ///
+ /// Creates a field interception combat engagement where defenders meet attackers before they reach the target castle.
+ /// CORE INNOVATION: Allows strategic defensive positioning and prevents inevitable castle sieges.
+ ///
+ /// The player initiating the attack
+ /// The player defending (can intercept in the field)
+ /// Where the field battle takes place
+ /// Attacking army composition and equipment
+ /// Defending army composition and equipment
+ /// The kingdom context for the combat
+ /// Battle parameters, terrain effects, and special conditions
+ /// Cancellation token for async operation
+ /// Created combat log with field interception battle results
+ /// Thrown when parameters are invalid or interception is not allowed
+ /// Thrown when field interception cannot be initiated
+ /// Thrown when operation is cancelled
+ Task CreateFieldInterceptionCombatAsync(int attackingPlayerId, int defendingPlayerId,
+ (int X, int Y) interceptionCoordinates, object attackingForce, object defendingForce, int kingdomId,
+ object combatConfiguration, CancellationToken cancellationToken = default);
+
+ ///
+ /// Validates if field interception is possible based on army positions, movement speeds, timing windows,
+ /// and strategic positioning. Calculates interception probability and optimal positioning.
+ ///
+ /// The attacking player
+ /// The potential intercepting player
+ /// The original target of the attack
+ /// The kingdom context for validation
+ /// Cancellation token for async operation
+ /// Interception feasibility analysis with optimal positioning recommendations
+ /// Thrown when parameters are invalid
+ /// Thrown when operation is cancelled
+ Task<(bool CanIntercept, double InterceptionProbability, (int X, int Y)[] OptimalPositions, TimeSpan TimeWindow)>
+ ValidateFieldInterceptionAsync(int attackingPlayerId, int defendingPlayerId, (int X, int Y) targetCoordinates,
+ int kingdomId, CancellationToken cancellationToken = default);
+
+ ///
+ /// Gets active field interception opportunities for alliance members and kingdom defenders.
+ /// Identifies incoming attacks that can be intercepted and calculates strategic value.
+ ///
+ /// The player looking for interception opportunities
+ /// Radius around player to search for interception opportunities
+ /// The kingdom context for the search
+ /// Cancellation token for async operation
+ /// Available interception opportunities with strategic analysis
+ /// Thrown when parameters are invalid
+ /// Thrown when operation is cancelled
+ Task>
+ GetFieldInterceptionOpportunitiesAsync(int defendingPlayerId, int searchRadius, int kingdomId,
+ CancellationToken cancellationToken = default);
+
+ ///
+ /// Processes field interception battle resolution using statistical combat system with attack/defense/health
+ /// calculations, damage modifiers, dragon bonuses, and equipment effects.
+ ///
+ /// The combat engagement to resolve
+ /// Combat calculations, random factors, and environmental effects
+ /// The kingdom context for the battle
+ /// Cancellation token for async operation
+ /// Updated combat log with battle resolution and casualty reports
+ /// Thrown when parameters are invalid or combat already resolved
+ /// Thrown when battle resolution fails
+ /// Thrown when operation is cancelled
+ Task ResolveFieldInterceptionBattleAsync(int combatLogId, object battleParameters, int kingdomId,
+ CancellationToken cancellationToken = default);
+
+ #endregion
+
+ #region Attack Classification System
+
+ ///
+ /// Classifies attack types based on army composition, target selection, and strategic intent.
+ /// Ranges from Lightning Raids (unrestricted) to Castle Sieges (fully restricted by field interception).
+ ///
+ /// The attacking player
+ /// The target location
+ /// Army size, composition, and equipment
+ /// The kingdom context for classification
+ /// Cancellation token for async operation
+ /// Attack classification with interception rules and restrictions
+ /// Thrown when parameters are invalid
+ /// Thrown when operation is cancelled
+ Task<(string AttackType, string[] InterceptionRules, double VulnerabilityFactor)> ClassifyAttackTypeAsync(
+ int attackingPlayerId, (int X, int Y) targetCoordinates, object armyComposition, int kingdomId,
+ CancellationToken cancellationToken = default);
+
+ ///
+ /// Gets combat logs filtered by attack classification for strategic analysis and defensive planning.
+ /// Helps identify attack patterns and defensive effectiveness by attack type.
+ ///
+ /// The attack classification to filter by
+ /// The kingdom context for the search
+ /// Time period to analyze
+ /// Cancellation token for async operation
+ /// Combat logs matching the attack classification
+ /// Thrown when parameters are invalid
+ /// Thrown when operation is cancelled
+ Task> GetCombatLogsByAttackTypeAsync(string attackType, int kingdomId, TimeSpan timeRange,
+ CancellationToken cancellationToken = default);
+
+ ///
+ /// Analyzes attack effectiveness by classification, identifying successful strategies and defensive gaps.
+ /// Provides insights for both offensive planning and defensive improvements.
+ ///
+ /// The kingdom to analyze
+ /// Time period for analysis
+ /// Cancellation token for async operation
+ /// Attack effectiveness analysis by classification with strategic recommendations
+ /// Thrown when parameters are invalid
+ /// Thrown when operation is cancelled
+ Task AnalyzeAttackEffectivenessByTypeAsync(int kingdomId, TimeSpan analysisTimeframe,
+ CancellationToken cancellationToken = default);
+
+ #endregion
+
+ #region Speed Limitations and March Mechanics
+
+ ///
+ /// Calculates march times between coordinates considering minimum march times, diminishing returns on speed,
+ /// terrain effects, alliance territory bonuses, and temporary speed modifications.
+ ///
+ /// Starting position
+ /// Destination position
+ /// Army affecting march speed
+ /// Player for speed bonuses calculation
+ /// The kingdom context for calculations
+ /// Cancellation token for async operation
+ /// March time calculations with speed factors and arrival prediction
+ /// Thrown when parameters are invalid
+ /// Thrown when operation is cancelled
+ Task<(TimeSpan MarchTime, TimeSpan MinimumTime, double SpeedModifier, DateTime EstimatedArrival)>
+ CalculateMarchTimeAsync((int X, int Y) startCoordinates, (int X, int Y) endCoordinates,
+ object armyComposition, int playerId, int kingdomId, CancellationToken cancellationToken = default);
+
+ ///
+ /// Validates march legality based on speed limitations, grace periods, cooldown restrictions,
+ /// and movement rule violations. Prevents exploitation of speed mechanics.
+ ///
+ /// The player attempting the march
+ /// March details including target, army, and timing
+ /// The kingdom context for validation
+ /// Cancellation token for async operation
+ /// March validation result with restriction details and cooldown information
+ /// Thrown when parameters are invalid
+ /// Thrown when operation is cancelled
+ Task<(bool IsAllowed, string[] Restrictions, TimeSpan? RequiredWait)> ValidateMarchLegalityAsync(
+ int playerId, object marchConfiguration, int kingdomId, CancellationToken cancellationToken = default);
+
+ ///
+ /// Records march history for speed limitation enforcement and pattern analysis.
+ /// Tracks march frequency, destinations, and timing to prevent exploitation.
+ ///
+ /// The player making the march
+ /// Complete march information
+ /// The kingdom context for recording
+ /// Cancellation token for async operation
+ /// Updated march history with timing validation
+ /// Thrown when parameters are invalid
+ /// Thrown when march recording fails
+ /// Thrown when operation is cancelled
+ Task RecordMarchHistoryAsync(int playerId, object marchDetails, int kingdomId,
+ CancellationToken cancellationToken = default);
+
+ ///
+ /// Gets march analytics for players including frequency patterns, preferred targets,
+ /// timing strategies, and effectiveness metrics for behavioral analysis.
+ ///
+ /// The player to analyze
+ /// The kingdom context for analysis
+ /// Time period for march analysis
+ /// Cancellation token for async operation
+ /// Comprehensive march behavior analysis
+ /// Thrown when parameters are invalid
+ /// Thrown when operation is cancelled
+ Task GetPlayerMarchAnalyticsAsync(int playerId, int kingdomId, TimeSpan analysisTimeframe,
+ CancellationToken cancellationToken = default);
+
+ #endregion
+
+ #region Stealth and Route Planning
+
+ ///
+ /// Creates stealth march plans with hidden routes and timing to avoid detection and interception.
+ /// Balances free strategic planning with premium convenience options for route optimization.
+ ///
+ /// The player planning the stealth march
+ /// The intended target
+ /// Stealth parameters and route preferences
+ /// The kingdom context for planning
+ /// Cancellation token for async operation
+ /// Stealth march plan with route options and detection probability
+ /// Thrown when parameters are invalid or stealth not available
+ /// Thrown when stealth planning fails
+ /// Thrown when operation is cancelled
+ Task CreateStealthMarchPlanAsync(int playerId, (int X, int Y) targetCoordinates,
+ object stealthConfiguration, int kingdomId, CancellationToken cancellationToken = default);
+
+ ///
+ /// Detects stealth marches based on intelligence networks, scout reports, and detection systems.
+ /// Provides early warning for defended territories and alliance coordination.
+ ///
+ /// The player with detection capabilities
+ /// Area to scan for stealth marches
+ /// The kingdom context for detection
+ /// Cancellation token for async operation
+ /// Detected stealth marches with confidence levels and estimated targets
+ /// Thrown when parameters are invalid
+ /// Thrown when operation is cancelled
+ Task>
+ DetectStealthMarchesAsync(int defendingPlayerId, int detectionRadius, int kingdomId,
+ CancellationToken cancellationToken = default);
+
+ ///
+ /// Validates route planning options based on player access level (free vs premium features).
+ /// Ensures skill-based alternatives exist while providing convenience options for premium users.
+ ///
+ /// The player planning routes
+ /// Desired route characteristics
+ /// The kingdom context for validation
+ /// Cancellation token for async operation
+ /// Available route planning options with feature access levels
+ /// Thrown when parameters are invalid
+ /// Thrown when operation is cancelled
+ Task<(object[] FreeOptions, object[] PremiumOptions, string[] SkillBasedAlternatives)>
+ ValidateRoutePlanningAccessAsync(int playerId, object routePreferences, int kingdomId,
+ CancellationToken cancellationToken = default);
+
+ #endregion
+
+ #region Dragon Integration and Combat Bonuses
+
+ ///
+ /// Applies dragon bonuses to combat calculations including skill-based buffs, equipment effects,
+ /// and evolution bonuses. Dragons must accompany armies and provide strategic advantages.
+ ///
+ /// The combat engagement to apply dragon bonuses to
+ /// Attacking player's dragon setup
+ /// Defending player's dragon setup
+ /// The kingdom context for the combat
+ /// Cancellation token for async operation
+ /// Updated combat log with dragon bonus calculations
+ /// Thrown when parameters are invalid or dragons not present
+ /// Thrown when dragon bonus application fails
+ /// Thrown when operation is cancelled
+ Task ApplyDragonBonusesToCombatAsync(int combatLogId, object attackingDragonConfiguration,
+ object defendingDragonConfiguration, int kingdomId, CancellationToken cancellationToken = default);
+
+ ///
+ /// Validates dragon participation in combat based on army composition, dragon stamina,
+ /// skill compatibility, and equipment requirements for combat engagement.
+ ///
+ /// The player with the dragon
+ /// Dragon skills, equipment, and status
+ /// Army the dragon will accompany
+ /// The kingdom context for validation
+ /// Cancellation token for async operation
+ /// Dragon participation validation with skill effectiveness prediction
+ /// Thrown when parameters are invalid
+ /// Thrown when operation is cancelled
+ Task<(bool CanParticipate, double EffectivenessModifier, string[] SkillBonuses, string[] Restrictions)>
+ ValidateDragonParticipationAsync(int playerId, object dragonConfiguration, object armyComposition,
+ int kingdomId, CancellationToken cancellationToken = default);
+
+ ///
+ /// Gets dragon combat performance analytics including skill effectiveness, equipment impact,
+ /// evolution benefits, and strategic value in different combat scenarios.
+ ///
+ /// The player to analyze dragon performance for
+ /// The kingdom context for analysis
+ /// Time period for dragon performance analysis
+ /// Cancellation token for async operation
+ /// Dragon performance analytics with optimization recommendations
+ /// Thrown when parameters are invalid
+ /// Thrown when operation is cancelled
+ Task GetDragonCombatAnalyticsAsync(int playerId, int kingdomId, TimeSpan analysisTimeframe,
+ CancellationToken cancellationToken = default);
+
+ #endregion
+
+ #region KvK Combat Events
+
+ ///
+ /// Creates large-scale KvK combat events involving multiple kingdoms, alliances, and coalition forces.
+ /// Handles complex battle scenarios with kingdom vs kingdom mechanics and territory control.
+ ///
+ /// Kingdoms involved in the KvK combat
+ /// Type of KvK event (3-kingdom war, alliance conquest, etc.)
+ /// Terrain, objectives, and victory conditions
+ /// Alliance coalitions and their battle formations
+ /// Cancellation token for async operation
+ /// Created KvK combat event with initial battle state
+ /// Thrown when parameters are invalid or kingdoms ineligible
+ /// Thrown when KvK event creation fails
+ /// Thrown when operation is cancelled
+ Task CreateKvKCombatEventAsync(IEnumerable participatingKingdoms, string eventType,
+ object battlefieldConfiguration, object coalitionArrangements, CancellationToken cancellationToken = default);
+
+ ///
+ /// Tracks KvK battle progression including territory control changes, casualty reports,
+ /// strategic objective completion, and coalition performance metrics.
+ ///
+ /// The KvK combat event to track
+ /// Current battle state and changes
+ /// Cancellation token for async operation
+ /// Updated KvK combat log with battle progression
+ /// Thrown when parameters are invalid or combat not found
+ /// Thrown when battle tracking fails
+ /// Thrown when operation is cancelled
+ Task TrackKvKBattleProgressionAsync(int kvkCombatId, object battleUpdates,
+ CancellationToken cancellationToken = default);
+
+ ///
+ /// Resolves KvK combat events with multiple victory paths including military dominance,
+ /// economic control, diplomatic success, and technological advancement.
+ ///
+ /// The KvK combat event to resolve
+ /// Conditions met for victory determination
+ /// Cancellation token for async operation
+ /// Resolved KvK combat log with victory outcomes and rewards distribution
+ /// Thrown when parameters are invalid or combat already resolved
+ /// Thrown when KvK resolution fails
+ /// Thrown when operation is cancelled
+ Task ResolveKvKCombatEventAsync(int kvkCombatId, object victoryConditions,
+ CancellationToken cancellationToken = default);
+
+ ///
+ /// Gets KvK combat history for kingdoms including participation records, performance metrics,
+ /// victory/defeat ratios, and strategic lessons learned for future matchmaking.
+ ///
+ /// The kingdom to get KvK history for
+ /// Time period for historical analysis
+ /// Cancellation token for async operation
+ /// KvK combat history with performance trends and strategic insights
+ /// Thrown when parameters are invalid
+ /// Thrown when operation is cancelled
+ Task GetKvKCombatHistoryAsync(int kingdomId, TimeSpan historyTimeframe,
+ CancellationToken cancellationToken = default);
+
+ #endregion
+
+ #region Forest Barrier and Banishment Mechanics
+
+ ///
+ /// Applies forest barrier speed penalties (50% reduction) for players crossing into contested forest zones
+ /// during KvK events. Handles terrain-based movement restrictions and strategic positioning.
+ ///
+ /// The player entering forest barriers
+ /// The forest zone coordinates
+ /// Crossing attempt details and timing
+ /// The kingdom context for the crossing
+ /// Cancellation token for async operation
+ /// Forest crossing result with speed penalties and strategic implications
+ /// Thrown when parameters are invalid or crossing not allowed
+ /// Thrown when forest crossing fails
+ /// Thrown when operation is cancelled
+ Task ApplyForestBarrierPenaltyAsync(int playerId, (int X, int Y) forestCoordinates,
+ object crossingConfiguration, int kingdomId, CancellationToken cancellationToken = default);
+
+ ///
+ /// Processes castle banishment for players who lose battles in contested forest zones.
+ /// Handles forced teleportation, temporary restrictions, and recovery mechanics.
+ ///
+ /// The player being banished from their castle
+ /// Combat result or event causing banishment
+ /// How long the banishment lasts
+ /// The kingdom context for banishment
+ /// Cancellation token for async operation
+ /// Banishment result with recovery options and timeline
+ /// Thrown when parameters are invalid or banishment not justified
+ /// Thrown when banishment processing fails
+ /// Thrown when operation is cancelled
+ Task ProcessCastleBanishmentAsync(int banishedPlayerId, object banishmentTrigger,
+ TimeSpan banishmentDuration, int kingdomId, CancellationToken cancellationToken = default);
+
+ ///
+ /// Gets forest zone control status including alliance territorial claims, contested areas,
+ /// and strategic resource locations that trigger barrier mechanics during conflicts.
+ ///
+ /// The forest zone to analyze
+ /// The kingdom context for analysis
+ /// Cancellation token for async operation
+ /// Forest zone control analysis with territorial disputes and strategic value
+ /// Thrown when parameters are invalid
+ /// Thrown when operation is cancelled
+ Task GetForestZoneControlStatusAsync(int forestZoneId, int kingdomId,
+ CancellationToken cancellationToken = default);
+
+ #endregion
+
+ #region Combat Analytics and Intelligence
+
+ ///
+ /// Gets comprehensive combat analytics for players including win/loss ratios, effectiveness by attack type,
+ /// field interception success rates, and strategic pattern analysis for performance improvement.
+ ///
+ /// The player to analyze
+ /// The kingdom context for analysis
+ /// Time period for combat analysis
+ /// Cancellation token for async operation
+ /// Detailed combat performance analytics with improvement recommendations
+ /// Thrown when parameters are invalid
+ /// Thrown when operation is cancelled
+ Task GetPlayerCombatAnalyticsAsync(int playerId, int kingdomId, TimeSpan analysisTimeframe,
+ CancellationToken cancellationToken = default);
+
+ ///
+ /// Generates combat intelligence reports for alliances including threat assessment, enemy patterns,
+ /// strategic vulnerabilities, and recommended defensive posturing for alliance coordination.
+ ///
+ /// The alliance requesting intelligence
+ /// The kingdom context for intelligence
+ /// Local threats, kingdom-wide, or KvK intelligence
+ /// Cancellation token for async operation
+ /// Combat intelligence report with threat analysis and strategic recommendations
+ /// Thrown when parameters are invalid
+ /// Thrown when operation is cancelled
+ Task GenerateAllianceCombatIntelligenceAsync(int allianceId, int kingdomId, string intelligenceScope,
+ CancellationToken cancellationToken = default);
+
+ ///
+ /// Gets kingdom combat statistics including overall military activity, power distribution,
+ /// alliance conflicts, and readiness for KvK events for administrative and strategic planning.
+ ///
+ /// The kingdom to analyze
+ /// Time period for statistical analysis
+ /// Cancellation token for async operation
+ /// Kingdom combat statistics with military readiness assessment
+ /// Thrown when parameters are invalid
+ /// Thrown when operation is cancelled
+ Task GetKingdomCombatStatisticsAsync(int kingdomId, TimeSpan statisticsTimeframe,
+ CancellationToken cancellationToken = default);
+
+ ///
+ /// Analyzes combat effectiveness of different troop compositions, equipment combinations,
+ /// and strategic approaches to provide data-driven optimization recommendations.
+ ///
+ /// Combat scenarios and variables to analyze
+ /// The kingdom context for analysis
+ /// Cancellation token for async operation
+ /// Combat effectiveness analysis with optimization recommendations
+ /// Thrown when parameters are invalid
+ /// Thrown when operation is cancelled
+ Task AnalyzeCombatEffectivenessAsync(object combatParameters, int kingdomId,
+ CancellationToken cancellationToken = default);
+
+ #endregion
+
+ #region Battle Resolution and Statistical Combat
+
+ ///
+ /// Processes statistical combat resolution using attack/defense/health calculations with damage modifiers,
+ /// critical hits, armor penetration, and tactical bonuses for realistic battle outcomes.
+ ///
+ /// The combat engagement to resolve
+ /// All factors affecting battle outcome
+ /// The kingdom context for resolution
+ /// Cancellation token for async operation
+ /// Resolved combat log with detailed battle results and casualty breakdown
+ /// Thrown when parameters are invalid or combat already resolved
+ /// Thrown when battle resolution fails
+ /// Thrown when operation is cancelled
+ Task ResolveStatisticalCombatAsync(int combatLogId, object combatParameters, int kingdomId,
+ CancellationToken cancellationToken = default);
+
+ ///
+ /// Calculates troop effectiveness modifiers based on tier differences, equipment quality,
+ /// research bonuses, alliance support, and environmental factors for accurate combat predictions.
+ ///
+ /// Attacking force composition and bonuses
+ /// Defending force composition and bonuses
+ /// Environmental and situational factors
+ /// The kingdom context for calculations
+ /// Cancellation token for async operation
+ /// Combat effectiveness calculations with modifier breakdown
+ /// Thrown when parameters are invalid
+ /// Thrown when operation is cancelled
+ Task CalculateTroopEffectivenessAsync(object attackingArmy, object defendingArmy,
+ object battleConditions, int kingdomId, CancellationToken cancellationToken = default);
+
+ ///
+ /// Simulates combat outcomes for strategic planning without actually conducting battles.
+ /// Provides probability distributions and expected results for tactical decision-making.
+ ///
+ /// Hypothetical combat scenarios to simulate
+ /// Number of simulation runs for statistical accuracy
+ /// The kingdom context for simulation
+ /// Cancellation token for async operation
+ /// Combat simulation results with probability analysis and outcome predictions
+ /// Thrown when parameters are invalid
+ /// Thrown when operation is cancelled
+ Task SimulateCombatOutcomesAsync(object simulationParameters, int simulationCount, int kingdomId,
+ CancellationToken cancellationToken = default);
+
+ #endregion
+ }
+}
\ No newline at end of file
diff --git a/ShadowedRealmsMobile/src/server/ShadowedRealms.Core/Interfaces/Repositories/IKingdomRepository.cs b/ShadowedRealmsMobile/src/server/ShadowedRealms.Core/Interfaces/Repositories/IKingdomRepository.cs
new file mode 100644
index 0000000..d1eeb09
--- /dev/null
+++ b/ShadowedRealmsMobile/src/server/ShadowedRealms.Core/Interfaces/Repositories/IKingdomRepository.cs
@@ -0,0 +1,358 @@
+/*
+ * File: /src/server/ShadowedRealms.Core/Interfaces/Repositories/IKingdomRepository.cs
+ * Created: 2025-10-19
+ * Last Modified: 2025-10-19
+ * Description: Kingdom repository interface defining kingdom-specific data access operations.
+ * Handles kingdom lifecycle, population management, KvK events, merger systems,
+ * and democratic political mechanics. Since Kingdom is the root scoping entity,
+ * this interface includes special operations for cross-kingdom queries when needed.
+ * Last Edit Notes: Initial implementation with population management, KvK systems, merger mechanics, and political operations.
+ */
+
+using ShadowedRealms.Core.Models;
+using ShadowedRealms.Core.Models.Kingdom;
+using System.Linq.Expressions;
+
+namespace ShadowedRealms.Core.Interfaces.Repositories
+{
+ ///
+ /// Repository interface for Kingdom entity operations, providing kingdom lifecycle management,
+ /// population control, KvK event coordination, merger systems, and democratic political mechanics.
+ /// This is the root repository that enables cross-kingdom operations when specifically needed.
+ ///
+ public interface IKingdomRepository : IRepository
+ {
+ #region Kingdom Lifecycle Management
+
+ ///
+ /// Creates a new kingdom with initial configuration and assigns it the next available kingdom number.
+ /// Automatically sets up default political structure and resource allocation systems.
+ ///
+ /// The name for the new kingdom
+ /// The server region where the kingdom will be hosted
+ /// Cancellation token for async operation
+ /// The newly created kingdom with initial configuration
+ /// Thrown when kingdomName is invalid or serverRegion is not supported
+ /// Thrown when kingdom creation fails due to system constraints
+ /// Thrown when operation is cancelled
+ Task CreateNewKingdomAsync(string kingdomName, string serverRegion,
+ CancellationToken cancellationToken = default);
+
+ ///
+ /// Gets all kingdoms that are currently accepting new players based on population thresholds.
+ /// Returns kingdoms with population below the maximum capacity (1,500 players) sorted by creation date.
+ ///
+ /// Cancellation token for async operation
+ /// Available kingdoms for new player registration
+ /// Thrown when operation is cancelled
+ Task> GetAvailableKingdomsForNewPlayersAsync(CancellationToken cancellationToken = default);
+
+ ///
+ /// Gets the newest kingdom that has space for new players, creating one if none exist.
+ /// This is used for the default kingdom assignment when players don't choose manually.
+ ///
+ /// The preferred server region for kingdom selection
+ /// Cancellation token for async operation
+ /// The newest available kingdom or a newly created one
+ /// Thrown when serverRegion is invalid
+ /// Thrown when kingdom selection/creation fails
+ /// Thrown when operation is cancelled
+ Task GetNewestAvailableKingdomAsync(string serverRegion,
+ CancellationToken cancellationToken = default);
+
+ ///
+ /// Archives a kingdom that no longer has active players or has been merged into another kingdom.
+ /// Preserves historical data while removing the kingdom from active matchmaking and operations.
+ ///
+ /// The ID of the kingdom to archive
+ /// The reason for archiving (merger, inactivity, etc.)
+ /// Cancellation token for async operation
+ /// True if kingdom was archived successfully
+ /// Thrown when kingdomId is invalid or kingdom cannot be archived
+ /// Thrown when kingdom has active players or pending operations
+ /// Thrown when operation is cancelled
+ Task ArchiveKingdomAsync(int kingdomId, string archiveReason,
+ CancellationToken cancellationToken = default);
+
+ #endregion
+
+ #region Population Management
+
+ ///
+ /// Gets the current population count for a specific kingdom including active and inactive players.
+ /// Used for kingdom capacity management and merger eligibility determination.
+ ///
+ /// The kingdom to get population for
+ /// Whether to include players who haven't logged in recently
+ /// Cancellation token for async operation
+ /// Current population statistics for the kingdom
+ /// Thrown when kingdomId is invalid
+ /// Thrown when operation is cancelled
+ Task<(int ActivePlayers, int InactivePlayers, int TotalPlayers)> GetKingdomPopulationAsync(int kingdomId,
+ bool includeInactive = false, CancellationToken cancellationToken = default);
+
+ ///
+ /// Gets kingdoms that are eligible for population-based merger based on low active player counts.
+ /// Returns kingdoms with fewer than the minimum viable population (typically 300-500 active players).
+ ///
+ /// The minimum population threshold for kingdom viability
+ /// Cancellation token for async operation
+ /// Kingdoms eligible for merger due to low population
+ /// Thrown when minimumViablePopulation is invalid
+ /// Thrown when operation is cancelled
+ Task> GetKingdomsEligibleForMergerAsync(int minimumViablePopulation = 400,
+ CancellationToken cancellationToken = default);
+
+ ///
+ /// Updates the population statistics for a kingdom, typically called when players join/leave.
+ /// Automatically triggers kingdom capacity events when thresholds are reached.
+ ///
+ /// The kingdom to update
+ /// The change in population (positive for joins, negative for leaves)
+ /// Cancellation token for async operation
+ /// Updated kingdom with new population statistics
+ /// Thrown when kingdomId is invalid
+ /// Thrown when population change would violate system constraints
+ /// Thrown when operation is cancelled
+ Task UpdateKingdomPopulationAsync(int kingdomId, int populationChange,
+ CancellationToken cancellationToken = default);
+
+ #endregion
+
+ #region KvK Event Management
+
+ ///
+ /// Gets kingdoms that are eligible for KvK matchmaking based on power levels, participation history,
+ /// and time zone compatibility. Uses multi-dimensional analysis beyond raw power comparison.
+ ///
+ /// The kingdom requesting matchmaking
+ /// The type of KvK event being organized
+ /// Cancellation token for async operation
+ /// Kingdoms eligible for KvK matchmaking with compatibility scores
+ /// Thrown when targetKingdomId is invalid or eventType is unsupported
+ /// Thrown when operation is cancelled
+ Task> GetKvKEligibleKingdomsAsync(int targetKingdomId,
+ string eventType, CancellationToken cancellationToken = default);
+
+ ///
+ /// Creates a new KvK event linking multiple kingdoms and initializes event-specific data structures.
+ /// Sets up coalition systems, territory assignments, and victory condition tracking.
+ ///
+ /// The kingdoms participating in the event
+ /// The type of KvK event (3-kingdom, alliance wars, etc.)
+ /// When the event begins
+ /// How long the event lasts
+ /// Cancellation token for async operation
+ /// The created KvK event with initial configuration
+ /// Thrown when parameters are invalid or kingdoms are ineligible
+ /// Thrown when event creation fails due to system constraints
+ /// Thrown when operation is cancelled
+ Task CreateKvKEventAsync(IEnumerable participatingKingdomIds, string eventType,
+ DateTime startDate, TimeSpan duration, CancellationToken cancellationToken = default);
+
+ ///
+ /// Gets the current KvK events that a kingdom is participating in, including event status and performance metrics.
+ /// Returns both active events and recent historical events for context.
+ ///
+ /// The kingdom to get KvK events for
+ /// Whether to include completed events from the last 30 days
+ /// Cancellation token for async operation
+ /// KvK events associated with the kingdom
+ /// Thrown when kingdomId is invalid
+ /// Thrown when operation is cancelled
+ Task> GetKingdomKvKEventsAsync(int kingdomId, bool includeHistorical = false,
+ CancellationToken cancellationToken = default);
+
+ ///
+ /// Updates KvK performance metrics for a kingdom based on event participation and outcomes.
+ /// Affects future matchmaking and influences kingdom power ratings.
+ ///
+ /// The kingdom to update
+ /// The outcome of the KvK event
+ /// Detailed participation statistics
+ /// Cancellation token for async operation
+ /// Updated kingdom with new KvK performance data
+ /// Thrown when parameters are invalid
+ /// Thrown when update fails due to business rules
+ /// Thrown when operation is cancelled
+ Task UpdateKvKPerformanceAsync(int kingdomId, object eventResult, object participationMetrics,
+ CancellationToken cancellationToken = default);
+
+ #endregion
+
+ #region Kingdom Merger System
+
+ ///
+ /// Initiates a merger proposal between two kingdoms, starting the democratic voting process.
+ /// Both kingdoms must vote to approve the merger for it to proceed.
+ ///
+ /// The kingdom proposing the merger
+ /// The kingdom being invited to merge
+ /// The rationale for the merger proposal
+ /// Cancellation token for async operation
+ /// The merger proposal with voting configuration
+ /// Thrown when kingdom IDs are invalid or kingdoms are ineligible
+ /// Thrown when merger proposal cannot be created
+ /// Thrown when operation is cancelled
+ Task ProposeMergerAsync(int initiatingKingdomId, int targetKingdomId, string proposalReason,
+ CancellationToken cancellationToken = default);
+
+ ///
+ /// Gets kingdoms that are compatible for merger based on population, power levels, play styles,
+ /// and cultural compatibility. Used for suggesting merger partners to struggling kingdoms.
+ ///
+ /// The kingdom seeking merger partners
+ /// Cancellation token for async operation
+ /// Compatible kingdoms with compatibility scores and merger benefits analysis
+ /// Thrown when kingdomId is invalid
+ /// Thrown when operation is cancelled
+ Task> GetMergerCompatibleKingdomsAsync(
+ int kingdomId, CancellationToken cancellationToken = default);
+
+ ///
+ /// Executes an approved merger between two kingdoms, transferring all players, alliances, and resources
+ /// to the surviving kingdom while preserving historical data and alliance relationships.
+ ///
+ /// The kingdom that will continue to exist
+ /// The kingdom that will be absorbed
+ /// Settings for how the merger should be executed
+ /// Cancellation token for async operation
+ /// The updated surviving kingdom with merged population and resources
+ /// Thrown when parameters are invalid or merger is not approved
+ /// Thrown when merger execution fails
+ /// Thrown when operation is cancelled
+ Task ExecuteMergerAsync(int survivingKingdomId, int mergingKingdomId, object mergerConfiguration,
+ CancellationToken cancellationToken = default);
+
+ #endregion
+
+ #region Democratic Political System
+
+ ///
+ /// Gets the current royal court members for a kingdom including elected positions and appointed roles.
+ /// Returns the democratic leadership structure with terms, election dates, and approval ratings.
+ ///
+ /// The kingdom to get leadership for
+ /// Cancellation token for async operation
+ /// Current royal court structure with leadership details
+ /// Thrown when kingdomId is invalid
+ /// Thrown when operation is cancelled
+ Task GetKingdomRoyalCourtAsync(int kingdomId, CancellationToken cancellationToken = default);
+
+ ///
+ /// Initiates an election for a royal position within the kingdom's democratic system.
+ /// Sets up the voting process, candidate registration, and election timeline.
+ ///
+ /// The kingdom holding the election
+ /// The royal position being elected (King, Chancellor, etc.)
+ /// How long the election period lasts
+ /// Cancellation token for async operation
+ /// The election configuration with voting details
+ /// Thrown when parameters are invalid or election cannot be held
+ /// Thrown when election initiation fails
+ /// Thrown when operation is cancelled
+ Task InitiateRoyalElectionAsync(int kingdomId, string position, TimeSpan electionDuration,
+ CancellationToken cancellationToken = default);
+
+ ///
+ /// Updates the tax distribution settings for a kingdom based on royal court decisions.
+ /// Manages the 4% resource tax on conquered kingdoms and how it's distributed among citizens.
+ ///
+ /// The kingdom to update tax settings for
+ /// The new tax distribution configuration
+ /// The royal court member authorizing the change
+ /// Cancellation token for async operation
+ /// Updated kingdom with new tax distribution settings
+ /// Thrown when parameters are invalid or player lacks authority
+ /// Thrown when tax update fails due to business rules
+ /// Thrown when operation is cancelled
+ Task UpdateTaxDistributionAsync(int kingdomId, object taxDistributionRules, int authorizingPlayerId,
+ CancellationToken cancellationToken = default);
+
+ ///
+ /// Gets kingdoms that have conquered other kingdoms and are collecting the 4% resource tax.
+ /// Returns the tax collection status and distribution metrics for royal court oversight.
+ ///
+ /// The kingdom to get tax information for
+ /// Cancellation token for async operation
+ /// Tax collection and distribution details
+ /// Thrown when kingdomId is invalid
+ /// Thrown when operation is cancelled
+ Task GetKingdomTaxStatusAsync(int kingdomId, CancellationToken cancellationToken = default);
+
+ #endregion
+
+ #region Analytics and Reporting
+
+ ///
+ /// Gets comprehensive kingdom statistics including population trends, economic metrics,
+ /// military strength, and social engagement data for administrative analysis.
+ ///
+ /// The kingdom to get statistics for
+ /// The time period to analyze (last 7 days, 30 days, etc.)
+ /// Cancellation token for async operation
+ /// Detailed kingdom analytics and performance metrics
+ /// Thrown when parameters are invalid
+ /// Thrown when operation is cancelled
+ Task GetKingdomAnalyticsAsync(int kingdomId, TimeSpan timeRange,
+ CancellationToken cancellationToken = default);
+
+ ///
+ /// Gets kingdom performance metrics compared to other kingdoms in the same server region.
+ /// Provides percentile rankings for population, activity, military strength, and economic health.
+ ///
+ /// The kingdom to benchmark
+ /// The server region for comparison
+ /// Cancellation token for async operation
+ /// Benchmark analysis with percentile rankings
+ /// Thrown when parameters are invalid
+ /// Thrown when operation is cancelled
+ Task GetKingdomBenchmarkAnalysisAsync(int kingdomId, string serverRegion,
+ CancellationToken cancellationToken = default);
+
+ ///
+ /// Generates a kingdom health report identifying potential issues like population decline,
+ /// economic problems, or social tensions that might require intervention.
+ ///
+ /// The kingdom to analyze
+ /// Cancellation token for async operation
+ /// Kingdom health assessment with recommended actions
+ /// Thrown when kingdomId is invalid
+ /// Thrown when operation is cancelled
+ Task GenerateKingdomHealthReportAsync(int kingdomId, CancellationToken cancellationToken = default);
+
+ #endregion
+
+ #region Cross-Kingdom Operations (Special Authorization)
+
+ ///
+ /// Gets all kingdoms in the system - SPECIAL METHOD that bypasses kingdom scoping.
+ /// Should only be used for administrative operations and system-level analytics.
+ /// Requires special authorization and should be logged for security audit.
+ ///
+ /// Whether to include archived kingdoms
+ /// The admin ID authorizing this cross-kingdom access
+ /// Cancellation token for async operation
+ /// All kingdoms in the system
+ /// Thrown when admin authorization is invalid
+ /// Thrown when operation is cancelled
+ Task> GetAllKingdomsAsync(bool includeArchived = false, int? authorizingAdminId = null,
+ CancellationToken cancellationToken = default);
+
+ ///
+ /// Searches for kingdoms across all servers by name or other criteria.
+ /// SPECIAL METHOD for administrative use that bypasses normal kingdom scoping.
+ ///
+ /// The search parameters
+ /// The admin ID authorizing this cross-kingdom search
+ /// Cancellation token for async operation
+ /// Kingdoms matching the search criteria across all servers
+ /// Thrown when searchCriteria is null
+ /// Thrown when admin authorization is invalid
+ /// Thrown when operation is cancelled
+ Task> SearchKingdomsGloballyAsync(object searchCriteria, int authorizingAdminId,
+ CancellationToken cancellationToken = default);
+
+ #endregion
+ }
+}
\ No newline at end of file
diff --git a/ShadowedRealmsMobile/src/server/ShadowedRealms.Core/Interfaces/Repositories/IPlayerRepository.cs b/ShadowedRealmsMobile/src/server/ShadowedRealms.Core/Interfaces/Repositories/IPlayerRepository.cs
new file mode 100644
index 0000000..a52fb8f
--- /dev/null
+++ b/ShadowedRealmsMobile/src/server/ShadowedRealms.Core/Interfaces/Repositories/IPlayerRepository.cs
@@ -0,0 +1,562 @@
+/*
+ * File: /src/server/ShadowedRealms.Core/Interfaces/Repositories/IPlayerRepository.cs
+ * Created: 2025-10-19
+ * Last Modified: 2025-10-19
+ * Description: Player repository interface defining player-specific data access operations.
+ * Handles castle progression, troop management, resource systems, VIP mechanics,
+ * teleportation, research, equipment, and all core gameplay features for individual players.
+ * All operations are kingdom-scoped to prevent cross-kingdom data access.
+ * Last Edit Notes: Initial implementation with comprehensive player mechanics, VIP system, teleportation, and gameplay features.
+ */
+
+using ShadowedRealms.Core.Models;
+using ShadowedRealms.Core.Models.Player;
+using System.Linq.Expressions;
+
+namespace ShadowedRealms.Core.Interfaces.Repositories
+{
+ ///
+ /// Repository interface for Player entity operations, providing comprehensive player lifecycle management,
+ /// castle progression, troop systems, resource management, VIP mechanics, and all core gameplay features.
+ /// All operations maintain kingdom-scoped security to prevent cross-kingdom data access.
+ ///
+ public interface IPlayerRepository : IRepository
+ {
+ #region Player Lifecycle and Authentication
+
+ ///
+ /// Creates a new player account within the specified kingdom with initial starting resources and configuration.
+ /// Automatically assigns starting position, beginner protection, and tutorial progress tracking.
+ ///
+ /// The player's chosen username (must be unique within kingdom)
+ /// The kingdom where the player will be created
+ /// Initial player setup including position and resources
+ /// Cancellation token for async operation
+ /// The newly created player with starting configuration applied
+ /// Thrown when username is invalid, taken, or kingdom is full
+ /// Thrown when player creation fails due to system constraints
+ /// Thrown when operation is cancelled
+ Task CreateNewPlayerAsync(string username, int kingdomId, object startingConfiguration,
+ CancellationToken cancellationToken = default);
+
+ ///
+ /// Gets a player by their username within the specified kingdom context.
+ /// Used for login authentication and player lookup operations.
+ ///
+ /// The player's username to search for
+ /// The kingdom context for the search
+ /// Cancellation token for async operation
+ /// The player if found within the kingdom, null otherwise
+ /// Thrown when username is null/empty or kingdomId is invalid
+ /// Thrown when operation is cancelled
+ Task GetPlayerByUsernameAsync(string username, int kingdomId,
+ CancellationToken cancellationToken = default);
+
+ ///
+ /// Updates the player's last login time and activity status for kingdom population management.
+ /// Tracks login streaks, daily rewards eligibility, and alliance participation metrics.
+ ///
+ /// The player to update
+ /// The kingdom context for the operation
+ /// Additional login tracking data (IP, device, etc.)
+ /// Cancellation token for async operation
+ /// Updated player with new activity status
+ /// Thrown when playerId or kingdomId is invalid
+ /// Thrown when operation is cancelled
+ Task UpdatePlayerActivityAsync(int playerId, int kingdomId, object? loginMetrics = null,
+ CancellationToken cancellationToken = default);
+
+ ///
+ /// Gets players who have been inactive beyond the specified threshold for kingdom health monitoring.
+ /// Used for identifying accounts at risk of abandonment and triggering retention campaigns.
+ ///
+ /// The kingdom to check for inactive players
+ /// How long without login constitutes inactive
+ /// Cancellation token for async operation
+ /// Inactive players within the kingdom
+ /// Thrown when parameters are invalid
+ /// Thrown when operation is cancelled
+ Task> GetInactivePlayersAsync(int kingdomId, TimeSpan inactiveThreshold,
+ CancellationToken cancellationToken = default);
+
+ #endregion
+
+ #region Castle and Progression Management
+
+ ///
+ /// Upgrades a player's castle level, automatically updating capacity limits, unlocking features,
+ /// and applying resource costs. Validates upgrade requirements and prerequisite building levels.
+ ///
+ /// The player upgrading their castle
+ /// The target castle level (Launch cap: Level 30)
+ /// The kingdom context for the operation
+ /// Cancellation token for async operation
+ /// Updated player with new castle level and unlocked features
+ /// Thrown when parameters are invalid or upgrade is not allowed
+ /// Thrown when player lacks resources or prerequisites
+ /// Thrown when operation is cancelled
+ Task UpgradeCastleLevelAsync(int playerId, int targetLevel, int kingdomId,
+ CancellationToken cancellationToken = default);
+
+ ///
+ /// Gets players within a specific castle level range for matchmaking, event organization,
+ /// and progression analytics. Supports alliance recruitment and KvK balancing.
+ ///
+ /// Minimum castle level (inclusive)
+ /// Maximum castle level (inclusive)
+ /// The kingdom context for the search
+ /// Cancellation token for async operation
+ /// Players within the specified level range
+ /// Thrown when level parameters are invalid
+ /// Thrown when operation is cancelled
+ Task> GetPlayersByLevelRangeAsync(int minLevel, int maxLevel, int kingdomId,
+ CancellationToken cancellationToken = default);
+
+ ///
+ /// Gets the top players by castle level within the kingdom for leaderboards and recognition systems.
+ /// Includes progression speed metrics and recent advancement tracking.
+ ///
+ /// The kingdom to get top players from
+ /// Number of top players to return
+ /// Cancellation token for async operation
+ /// Top players ranked by castle level and progression metrics
+ /// Thrown when parameters are invalid
+ /// Thrown when operation is cancelled
+ Task> GetTopPlayersByCastleLevelAsync(int kingdomId, int topCount = 100,
+ CancellationToken cancellationToken = default);
+
+ ///
+ /// Updates building levels for a player's castle complex, validating prerequisites and resource costs.
+ /// Handles hospital, barracks, research facilities, and defensive structures.
+ ///
+ /// The player upgrading buildings
+ /// Dictionary of building types and target levels
+ /// The kingdom context for the operation
+ /// Cancellation token for async operation
+ /// Updated player with new building levels
+ /// Thrown when parameters are invalid or upgrades violate rules
+ /// Thrown when player lacks resources for upgrades
+ /// Thrown when operation is cancelled
+ Task UpdateBuildingLevelsAsync(int playerId, Dictionary buildingUpgrades, int kingdomId,
+ CancellationToken cancellationToken = default);
+
+ #endregion
+
+ #region Troop and Military Management
+
+ ///
+ /// Updates a player's troop counts for specific tier and type, validating capacity limits
+ /// and training requirements. Handles T1-T13 troops with tier-specific restrictions.
+ ///
+ /// The player whose troops are being updated
+ /// Dictionary of troop types and count changes
+ /// The kingdom context for the operation
+ /// Cancellation token for async operation
+ /// Updated player with new troop counts
+ /// Thrown when parameters are invalid or exceed capacity limits
+ /// Thrown when troop updates violate game rules
+ /// Thrown when operation is cancelled
+ Task UpdateTroopCountsAsync(int playerId, Dictionary troopUpdates, int kingdomId,
+ CancellationToken cancellationToken = default);
+
+ ///
+ /// Gets players by military strength for alliance recruitment, KvK balancing, and threat assessment.
+ /// Calculates total military power including troops, dragons, and equipment bonuses.
+ ///
+ /// The kingdom to search within
+ /// Minimum military power threshold
+ /// Cancellation token for async operation
+ /// Players meeting the minimum military power requirement
+ /// Thrown when parameters are invalid
+ /// Thrown when operation is cancelled
+ Task> GetPlayersByMilitaryStrengthAsync(int kingdomId, long minimumPower = 0,
+ CancellationToken cancellationToken = default);
+
+ ///
+ /// Records troop losses from combat, hospital capacity management, and death mechanics.
+ /// Handles wounded vs killed troops, hospital overflow, and resurrection systems.
+ ///
+ /// The player who suffered losses
+ /// Detailed breakdown of troop casualties
+ /// Combat information for loss calculations
+ /// The kingdom context for the operation
+ /// Cancellation token for async operation
+ /// Updated player with recorded losses and hospital status
+ /// Thrown when parameters are invalid
+ /// Thrown when loss recording fails
+ /// Thrown when operation is cancelled
+ Task RecordTroopLossesAsync(int playerId, object troopLosses, object combatContext, int kingdomId,
+ CancellationToken cancellationToken = default);
+
+ ///
+ /// Heals wounded troops in the hospital, consuming resources and time based on troop tier and count.
+ /// Supports instant healing with premium currency or time-based free healing.
+ ///
+ /// The player healing troops
+ /// Healing method, troops to heal, and resource costs
+ /// The kingdom context for the operation
+ /// Cancellation token for async operation
+ /// Updated player with healed troops and consumed resources
+ /// Thrown when parameters are invalid or player lacks resources
+ /// Thrown when healing fails due to game rules
+ /// Thrown when operation is cancelled
+ Task HealWoundedTroopsAsync(int playerId, object healingConfiguration, int kingdomId,
+ CancellationToken cancellationToken = default);
+
+ #endregion
+
+ #region Resource Management
+
+ ///
+ /// Updates a player's resource counts (food, wood, stone, iron, gold) validating capacity limits
+ /// and storage building requirements. Handles resource production, consumption, and transfers.
+ ///
+ /// The player whose resources are being updated
+ /// Dictionary of resource types and amount changes (positive or negative)
+ /// The kingdom context for the operation
+ /// Reason for the resource change (for logging)
+ /// Cancellation token for async operation
+ /// Updated player with new resource amounts
+ /// Thrown when parameters are invalid or exceed storage limits
+ /// Thrown when player lacks sufficient resources for deduction
+ /// Thrown when operation is cancelled
+ Task UpdateResourcesAsync(int playerId, Dictionary resourceChanges, int kingdomId,
+ string transactionReason, CancellationToken cancellationToken = default);
+
+ ///
+ /// Gets players with resource amounts within specified ranges for trading, alliance support,
+ /// and economic analysis. Supports finding players who can provide or need specific resources.
+ ///
+ /// The kingdom to search within
+ /// Resource type and amount range criteria
+ /// Cancellation token for async operation
+ /// Players matching the resource criteria
+ /// Thrown when parameters are invalid
+ /// Thrown when operation is cancelled
+ Task> GetPlayersByResourceCriteriaAsync(int kingdomId, Dictionary resourceCriteria,
+ CancellationToken cancellationToken = default);
+
+ ///
+ /// Processes resource production for a player based on building levels, research bonuses, and time elapsed.
+ /// Calculates production rates, applies bonuses, and updates storage with capacity limits.
+ ///
+ /// The player generating resources
+ /// Time period for resource generation
+ /// The kingdom context for the operation
+ /// Cancellation token for async operation
+ /// Updated player with produced resources
+ /// Thrown when parameters are invalid
+ /// Thrown when production calculation fails
+ /// Thrown when operation is cancelled
+ Task ProcessResourceProductionAsync(int playerId, TimeSpan productionDuration, int kingdomId,
+ CancellationToken cancellationToken = default);
+
+ #endregion
+
+ #region VIP System and Monetization
+
+ ///
+ /// Processes a VIP points purchase for a player, updating VIP level and unlocking benefits.
+ /// Handles VIP level progression, milestone rewards, and secret tier system integration.
+ ///
+ /// The player making the VIP purchase
+ /// Number of VIP points purchased
+ /// The kingdom context for the operation
+ /// Transaction details for purchase logging
+ /// Cancellation token for async operation
+ /// Updated player with new VIP status and rewards
+ /// Thrown when parameters are invalid
+ /// Thrown when VIP processing fails
+ /// Thrown when operation is cancelled
+ Task ProcessVipPurchaseAsync(int playerId, int vipPointsPurchased, int kingdomId, object purchaseDetails,
+ CancellationToken cancellationToken = default);
+
+ ///
+ /// Gets players by VIP level range for targeted offers, premium events, and customer service prioritization.
+ /// Supports VIP-specific matchmaking and exclusive content access management.
+ ///
+ /// The kingdom to search within
+ /// Minimum VIP level (inclusive)
+ /// Maximum VIP level (inclusive)
+ /// Cancellation token for async operation
+ /// Players within the specified VIP level range
+ /// Thrown when parameters are invalid
+ /// Thrown when operation is cancelled
+ Task> GetPlayersByVipLevelAsync(int kingdomId, int minVipLevel = 0, int maxVipLevel = int.MaxValue,
+ CancellationToken cancellationToken = default);
+
+ ///
+ /// Claims daily VIP rewards for a player based on their VIP level and login streak.
+ /// Prevents duplicate claims and calculates reward amounts based on VIP benefits.
+ ///
+ /// The player claiming rewards
+ /// The kingdom context for the operation
+ /// Cancellation token for async operation
+ /// Updated player with claimed rewards and updated claim status
+ /// Thrown when parameters are invalid
+ /// Thrown when rewards already claimed or player ineligible
+ /// Thrown when operation is cancelled
+ Task ClaimVipDailyRewardsAsync(int playerId, int kingdomId, CancellationToken cancellationToken = default);
+
+ ///
+ /// Gets VIP spending analytics for a player including lifetime value, purchase patterns, and chargeback risk.
+ /// Used for customer service, offer personalization, and financial risk management.
+ ///
+ /// The player to analyze
+ /// The kingdom context for the operation
+ /// Cancellation token for async operation
+ /// Comprehensive VIP spending analytics
+ /// Thrown when parameters are invalid
+ /// Thrown when operation is cancelled
+ Task GetPlayerVipAnalyticsAsync(int playerId, int kingdomId, CancellationToken cancellationToken = default);
+
+ #endregion
+
+ #region Teleportation and Movement
+
+ ///
+ /// Attempts to teleport a player to new coordinates, validating movement rules, proximity restrictions,
+ /// and teleportation costs. Handles free teleports, premium teleports, and alliance territory rules.
+ ///
+ /// The player requesting teleportation
+ /// The desired destination coordinates
+ /// Free, premium, or alliance-assisted teleport
+ /// The kingdom context for the operation
+ /// Cancellation token for async operation
+ /// Updated player with new coordinates if successful
+ /// Thrown when parameters are invalid or teleport violates rules
+ /// Thrown when player lacks resources or teleport is blocked
+ /// Thrown when operation is cancelled
+ Task TeleportPlayerAsync(int playerId, (int X, int Y) targetCoordinates, string teleportationType,
+ int kingdomId, CancellationToken cancellationToken = default);
+
+ ///
+ /// Gets players within a specific coordinate radius for local events, alliance recruitment,
+ /// and proximity-based interactions. Supports both circular and square search areas.
+ ///
+ /// The center point for the search
+ /// The search radius in coordinate units
+ /// The kingdom context for the search
+ /// Cancellation token for async operation
+ /// Players within the specified radius
+ /// Thrown when parameters are invalid
+ /// Thrown when operation is cancelled
+ Task> GetPlayersInRadiusAsync((int X, int Y) centerCoordinates, int radius, int kingdomId,
+ CancellationToken cancellationToken = default);
+
+ ///
+ /// Updates a player's movement speed modifiers based on research, equipment, and temporary effects.
+ /// Affects march times, teleportation cooldowns, and return speeds.
+ ///
+ /// The player to update
+ /// Dictionary of speed modifier sources and values
+ /// The kingdom context for the operation
+ /// Cancellation token for async operation
+ /// Updated player with new speed calculations
+ /// Thrown when parameters are invalid
+ /// Thrown when speed update fails
+ /// Thrown when operation is cancelled
+ Task UpdateMovementSpeedAsync(int playerId, Dictionary speedModifiers, int kingdomId,
+ CancellationToken cancellationToken = default);
+
+ ///
+ /// Validates if a teleportation is allowed based on game rules, proximity restrictions, and cooldowns.
+ /// Checks alliance territory rules, enemy proximity blocks, and teleportation history.
+ ///
+ /// The player requesting validation
+ /// The desired destination
+ /// The type of teleport being attempted
+ /// The kingdom context for validation
+ /// Cancellation token for async operation
+ /// Validation result with reasons for any restrictions
+ /// Thrown when parameters are invalid
+ /// Thrown when operation is cancelled
+ Task<(bool IsAllowed, string[] Restrictions, TimeSpan? Cooldown)> ValidateTeleportationAsync(int playerId,
+ (int X, int Y) targetCoordinates, string teleportationType, int kingdomId, CancellationToken cancellationToken = default);
+
+ #endregion
+
+ #region Research and Technology
+
+ ///
+ /// Updates a player's research progress in specific technology trees, validating prerequisites
+ /// and resource costs. Handles Military, Economic, and Technology research branches.
+ ///
+ /// The player conducting research
+ /// Dictionary of research areas and level increases
+ /// The kingdom context for the operation
+ /// Cancellation token for async operation
+ /// Updated player with new research levels and unlocked bonuses
+ /// Thrown when parameters are invalid or research violates prerequisites
+ /// Thrown when player lacks resources for research
+ /// Thrown when operation is cancelled
+ Task UpdateResearchProgressAsync(int playerId, Dictionary researchUpdates, int kingdomId,
+ CancellationToken cancellationToken = default);
+
+ ///
+ /// Gets players by research specialization for alliance coordination and strategic planning.
+ /// Identifies players with advanced military, economic, or technology research for specific roles.
+ ///
+ /// The kingdom to search within
+ /// Minimum research levels in specific areas
+ /// Cancellation token for async operation
+ /// Players meeting the research criteria
+ /// Thrown when parameters are invalid
+ /// Thrown when operation is cancelled
+ Task> GetPlayersByResearchSpecializationAsync(int kingdomId, Dictionary researchCriteria,
+ CancellationToken cancellationToken = default);
+
+ ///
+ /// Calculates total research bonuses for a player including base research, alliance research,
+ /// equipment bonuses, and temporary effects. Used for combat calculations and resource production.
+ ///
+ /// The player to calculate bonuses for
+ /// The kingdom context for the operation
+ /// Cancellation token for async operation
+ /// Comprehensive breakdown of all research bonuses
+ /// Thrown when parameters are invalid
+ /// Thrown when operation is cancelled
+ Task CalculateResearchBonusesAsync(int playerId, int kingdomId, CancellationToken cancellationToken = default);
+
+ #endregion
+
+ #region Equipment and Dragon System
+
+ ///
+ /// Updates a player's equipment loadout, validating equipment compatibility and enhancement levels.
+ /// Handles weapon, armor, and accessory systems with stat bonuses and set effects.
+ ///
+ /// The player updating equipment
+ /// Dictionary of equipment slots and new items
+ /// The kingdom context for the operation
+ /// Cancellation token for async operation
+ /// Updated player with new equipment and calculated stat bonuses
+ /// Thrown when parameters are invalid or equipment incompatible
+ /// Thrown when player lacks required items
+ /// Thrown when operation is cancelled
+ Task UpdateEquipmentAsync(int playerId, Dictionary equipmentChanges, int kingdomId,
+ CancellationToken cancellationToken = default);
+
+ ///
+ /// Updates a player's dragon configuration including skill selection, equipment, and evolution progress.
+ /// Dragons must accompany armies and provide skill-based buffs rather than pay-to-win advantages.
+ ///
+ /// The player updating their dragon
+ /// Dragon skills, equipment, and evolution settings
+ /// The kingdom context for the operation
+ /// Cancellation token for async operation
+ /// Updated player with new dragon configuration
+ /// Thrown when parameters are invalid or dragon config is incompatible
+ /// Thrown when player lacks required dragon resources
+ /// Thrown when operation is cancelled
+ Task UpdateDragonConfigurationAsync(int playerId, object dragonConfiguration, int kingdomId,
+ CancellationToken cancellationToken = default);
+
+ ///
+ /// Gets players by equipment power level for matchmaking, alliance organization, and competitive events.
+ /// Calculates total equipment score including enhancement levels and set bonuses.
+ ///
+ /// The kingdom to search within
+ /// Minimum equipment power threshold
+ /// Cancellation token for async operation
+ /// Players meeting the equipment power requirement
+ /// Thrown when parameters are invalid
+ /// Thrown when operation is cancelled
+ Task> GetPlayersByEquipmentPowerAsync(int kingdomId, long minimumEquipmentPower = 0,
+ CancellationToken cancellationToken = default);
+
+ #endregion
+
+ #region Alliance Integration
+
+ ///
+ /// Gets all players belonging to a specific alliance within the kingdom for alliance management operations.
+ /// Includes member roles, contribution metrics, and activity status.
+ ///
+ /// The alliance to get members for
+ /// The kingdom context for the operation
+ /// Cancellation token for async operation
+ /// All players who are members of the specified alliance
+ /// Thrown when parameters are invalid
+ /// Thrown when operation is cancelled
+ Task> GetAllianceMembersAsync(int allianceId, int kingdomId,
+ CancellationToken cancellationToken = default);
+
+ ///
+ /// Gets players without an alliance within the kingdom for recruitment and alliance invitation systems.
+ /// Filters by activity level, castle level, and availability for alliance participation.
+ ///
+ /// The kingdom to search within
+ /// Minimum castle level for alliance eligibility
+ /// Whether to only include recently active players
+ /// Cancellation token for async operation
+ /// Players available for alliance recruitment
+ /// Thrown when parameters are invalid
+ /// Thrown when operation is cancelled
+ Task> GetPlayersWithoutAllianceAsync(int kingdomId, int minimumCastleLevel = 1,
+ bool activeOnly = true, CancellationToken cancellationToken = default);
+
+ ///
+ /// Updates a player's alliance membership, handling alliance changes, role assignments, and contribution tracking.
+ /// Manages leaving previous alliance, cooldown periods, and integration into new alliance systems.
+ ///
+ /// The player changing alliance status
+ /// The new alliance ID (null for leaving alliance)
+ /// The role within the new alliance
+ /// The kingdom context for the operation
+ /// Cancellation token for async operation
+ /// Updated player with new alliance status
+ /// Thrown when parameters are invalid or alliance change violates rules
+ /// Thrown when alliance change fails due to cooldowns or restrictions
+ /// Thrown when operation is cancelled
+ Task UpdateAllianceMembershipAsync(int playerId, int? newAllianceId, string? membershipRole, int kingdomId,
+ CancellationToken cancellationToken = default);
+
+ #endregion
+
+ #region Player Analytics and Performance
+
+ ///
+ /// Gets comprehensive player performance analytics including combat effectiveness, economic efficiency,
+ /// social engagement, and progression metrics for administrative analysis and player development.
+ ///
+ /// The player to analyze
+ /// The kingdom context for the operation
+ /// The time period to analyze
+ /// Cancellation token for async operation
+ /// Detailed player analytics and performance metrics
+ /// Thrown when parameters are invalid
+ /// Thrown when operation is cancelled
+ Task GetPlayerAnalyticsAsync(int playerId, int kingdomId, TimeSpan timeRange,
+ CancellationToken cancellationToken = default);
+
+ ///
+ /// Gets player leaderboard rankings for various metrics including power, castle level, alliance contribution,
+ /// and KvK performance. Supports multiple ranking categories and time periods.
+ ///
+ /// The kingdom to generate rankings for
+ /// The metric to rank by (power, level, contribution, etc.)
+ /// Number of top players to return
+ /// Cancellation token for async operation
+ /// Top players ranked by the specified metric
+ /// Thrown when parameters are invalid
+ /// Thrown when operation is cancelled
+ Task> GetPlayerLeaderboardAsync(int kingdomId,
+ string rankingCategory, int topCount = 100, CancellationToken cancellationToken = default);
+
+ ///
+ /// Generates a player development report identifying strengths, weaknesses, and recommended improvement areas.
+ /// Provides personalized guidance for progression optimization and skill development.
+ ///
+ /// The player to generate report for
+ /// The kingdom context for the operation
+ /// Cancellation token for async operation
+ /// Comprehensive development report with recommendations
+ /// Thrown when parameters are invalid
+ /// Thrown when operation is cancelled
+ Task GeneratePlayerDevelopmentReportAsync(int playerId, int kingdomId,
+ CancellationToken cancellationToken = default);
+
+ #endregion
+ }
+}
\ No newline at end of file
diff --git a/ShadowedRealmsMobile/src/server/ShadowedRealms.Core/Interfaces/Repositories/IPurchaseLogRepository.cs b/ShadowedRealmsMobile/src/server/ShadowedRealms.Core/Interfaces/Repositories/IPurchaseLogRepository.cs
new file mode 100644
index 0000000..e0f743b
--- /dev/null
+++ b/ShadowedRealmsMobile/src/server/ShadowedRealms.Core/Interfaces/Repositories/IPurchaseLogRepository.cs
@@ -0,0 +1,442 @@
+/*
+ * File: /src/server/ShadowedRealms.Core/Interfaces/Repositories/IPurchaseLogRepository.cs
+ * Created: 2025-10-19
+ * Last Modified: 2025-10-19
+ * Description: Purchase log repository interface defining monetization-specific data access operations.
+ * Handles transaction tracking, chargeback protection, VIP progression, secret tier system,
+ * revenue analytics, fraud detection, and customer lifetime value analysis. Critical for
+ * financial integrity and anti-pay-to-win balance while maintaining sustainable revenue.
+ * Last Edit Notes: Initial implementation with comprehensive monetization tracking, VIP systems, and financial security.
+ */
+
+using ShadowedRealms.Core.Models;
+using ShadowedRealms.Core.Models.Purchase;
+using System.Linq.Expressions;
+
+namespace ShadowedRealms.Core.Interfaces.Repositories
+{
+ ///
+ /// Repository interface for PurchaseLog entity operations, providing comprehensive monetization management,
+ /// transaction tracking, chargeback protection, VIP progression, and revenue analytics.
+ /// Balances sustainable revenue generation with anti-pay-to-win principles and player value delivery.
+ ///
+ public interface IPurchaseLogRepository : IRepository
+ {
+ #region Transaction Processing and Validation
+
+ ///
+ /// Records a new purchase transaction with comprehensive validation, fraud detection, and VIP progression.
+ /// Automatically calculates VIP points, milestone rewards, and applies purchase benefits while logging for audit.
+ ///
+ /// The player making the purchase
+ /// Complete purchase information including items, prices, and payment method
+ /// The kingdom context for the purchase
+ /// External payment processor transaction ID
+ /// Cancellation token for async operation
+ /// Created purchase log with VIP progression and applied benefits
+ /// Thrown when parameters are invalid or purchase violates policies
+ /// Thrown when purchase processing fails due to fraud detection
+ /// Thrown when operation is cancelled
+ Task RecordPurchaseTransactionAsync(int playerId, object purchaseDetails, int kingdomId,
+ string transactionId, CancellationToken cancellationToken = default);
+
+ ///
+ /// Validates purchase eligibility based on player status, spending limits, cooldown periods,
+ /// and fraud prevention rules. Prevents exploitation while ensuring legitimate purchases proceed smoothly.
+ ///
+ /// The player attempting the purchase
+ /// Type of purchase being attempted
+ /// Dollar amount of the purchase
+ /// The kingdom context for validation
+ /// Cancellation token for async operation
+ /// Purchase eligibility result with restrictions and spending limit information
+ /// Thrown when parameters are invalid
+ /// Thrown when operation is cancelled
+ Task<(bool IsEligible, string[] Restrictions, decimal RemainingSpendingLimit, TimeSpan? Cooldown)>
+ ValidatePurchaseEligibilityAsync(int playerId, string purchaseType, decimal purchaseAmount, int kingdomId,
+ CancellationToken cancellationToken = default);
+
+ ///
+ /// Processes purchase refunds and reversals, handling VIP point adjustments, benefit revocation,
+ /// and account status updates. Maintains financial integrity while supporting customer service.
+ ///
+ /// The purchase being refunded
+ /// Reason for refund (customer service, chargeback, etc.)
+ /// Amount being refunded (can be partial)
+ /// The kingdom context for the refund
+ /// Admin authorizing the refund (if applicable)
+ /// Cancellation token for async operation
+ /// Updated purchase log with refund details and account adjustments
+ /// Thrown when parameters are invalid or refund not allowed
+ /// Thrown when refund processing fails
+ /// Thrown when operation is cancelled
+ Task ProcessPurchaseRefundAsync(int originalPurchaseId, string refundReason, decimal refundAmount,
+ int kingdomId, int? authorizingAdminId = null, CancellationToken cancellationToken = default);
+
+ ///
+ /// Verifies purchase authenticity with external payment processors to prevent fraud and ensure
+ /// transaction integrity. Cross-references with payment gateway records and validates receipt data.
+ ///
+ /// The purchase to verify
+ /// Data from external payment processor for verification
+ /// The kingdom context for verification
+ /// Cancellation token for async operation
+ /// Verification result with authenticity confirmation and fraud risk assessment
+ /// Thrown when parameters are invalid
+ /// Thrown when verification fails or fraud detected
+ /// Thrown when operation is cancelled
+ Task<(bool IsAuthentic, double FraudRiskScore, string[] VerificationFlags)> VerifyPurchaseAuthenticityAsync(
+ int purchaseLogId, object paymentProcessorData, int kingdomId, CancellationToken cancellationToken = default);
+
+ #endregion
+
+ #region VIP System Integration
+
+ ///
+ /// Calculates VIP point awards for purchases based on spending amount, purchase type, promotional bonuses,
+ /// and loyalty multipliers. Handles milestone detection and automatic VIP level progression.
+ ///
+ /// Dollar amount of purchase
+ /// Type of purchase for bonus calculations
+ /// Player for loyalty bonus calculations
+ /// The kingdom context for calculations
+ /// Cancellation token for async operation
+ /// VIP point calculation with milestone progression and bonus details
+ /// Thrown when parameters are invalid
+ /// Thrown when operation is cancelled
+ Task<(int VipPoints, int NewVipLevel, bool MilestoneReached, object[] UnlockedBenefits)>
+ CalculateVipPointsAsync(decimal purchaseAmount, string purchaseType, int playerId, int kingdomId,
+ CancellationToken cancellationToken = default);
+
+ ///
+ /// Processes VIP milestone rewards when players reach new VIP levels, including resource packages,
+ /// exclusive items, permanent bonuses, and secret tier system progression tracking.
+ ///
+ /// The player reaching the milestone
+ /// The VIP level just achieved
+ /// The purchase that triggered the milestone
+ /// The kingdom context for reward processing
+ /// Cancellation token for async operation
+ /// Processed milestone rewards with secret tier progression
+ /// Thrown when parameters are invalid or milestone already claimed
+ /// Thrown when milestone processing fails
+ /// Thrown when operation is cancelled
+ Task ProcessVipMilestoneRewardsAsync(int playerId, int newVipLevel, int triggeringPurchaseId,
+ int kingdomId, CancellationToken cancellationToken = default);
+
+ ///
+ /// Gets players by VIP spending tier for targeted offers, customer service prioritization,
+ /// and lifetime value analysis. Supports personalized monetization and retention strategies.
+ ///
+ /// The kingdom to analyze
+ /// The spending tier to filter by (whale, dolphin, minnow, F2P)
+ /// Time period for spending calculation
+ /// Cancellation token for async operation
+ /// Players in the specified spending tier with spending analytics
+ /// Thrown when parameters are invalid
+ /// Thrown when operation is cancelled
+ Task>
+ GetPlayersBySpendingTierAsync(int kingdomId, string spendingTier, TimeSpan timeframe,
+ CancellationToken cancellationToken = default);
+
+ ///
+ /// Tracks secret tier system progression inspired by King of Avalon's hidden VIP benefits.
+ /// Provides additional rewards and recognition for highest-tier spenders without publicizing exact thresholds.
+ ///
+ /// The player to track secret tier progression for
+ /// Recent purchase amount
+ /// The kingdom context for tracking
+ /// Cancellation token for async operation
+ /// Secret tier progression with unlocked benefits (if any)
+ /// Thrown when parameters are invalid
+ /// Thrown when operation is cancelled
+ Task TrackSecretTierProgressionAsync(int playerId, decimal purchaseAmount, int kingdomId,
+ CancellationToken cancellationToken = default);
+
+ #endregion
+
+ #region Chargeback Protection and Fraud Prevention
+
+ ///
+ /// Processes chargeback notifications from payment processors, automatically adjusting player accounts,
+ /// revoking purchased benefits, and implementing protective measures against future fraud attempts.
+ ///
+ /// The purchase being charged back
+ /// Details from payment processor about the chargeback
+ /// The kingdom context for chargeback processing
+ /// Cancellation token for async operation
+ /// Chargeback processing result with account adjustments and protective measures
+ /// Thrown when parameters are invalid or purchase not found
+ /// Thrown when chargeback processing fails
+ /// Thrown when operation is cancelled
+ Task ProcessChargebackAsync(int originalPurchaseId, object chargebackDetails, int kingdomId,
+ CancellationToken cancellationToken = default);
+
+ ///
+ /// Identifies high-risk purchase patterns that may indicate fraud, including rapid large purchases,
+ /// unusual payment methods, geographic inconsistencies, and behavioral anomalies for fraud prevention.
+ ///
+ /// The player to analyze for risk patterns
+ /// Recent purchase history for pattern analysis
+ /// The kingdom context for analysis
+ /// Cancellation token for async operation
+ /// Fraud risk assessment with specific risk factors and recommended actions
+ /// Thrown when parameters are invalid
+ /// Thrown when operation is cancelled
+ Task<(double RiskScore, string[] RiskFactors, string[] RecommendedActions, bool RequiresReview)>
+ AnalyzeFraudRiskPatternsAsync(int playerId, IEnumerable recentPurchases, int kingdomId,
+ CancellationToken cancellationToken = default);
+
+ ///
+ /// Implements protective measures for accounts with chargeback history, including purchase restrictions,
+ /// enhanced verification requirements, and monitoring protocols to prevent future losses.
+ ///
+ /// The player to implement protections for
+ /// Level of protection based on chargeback severity
+ /// The kingdom context for protection implementation
+ /// Cancellation token for async operation
+ /// Implemented protection measures with duration and review requirements
+ /// Thrown when parameters are invalid
+ /// Thrown when protection implementation fails
+ /// Thrown when operation is cancelled
+ Task ImplementChargebackProtectionAsync(int playerId, string protectionLevel, int kingdomId,
+ CancellationToken cancellationToken = default);
+
+ ///
+ /// Gets chargeback analytics for financial risk management including chargeback rates by payment method,
+ /// geographic patterns, player behavior correlations, and financial impact assessment.
+ ///
+ /// The kingdom to analyze (null for global analysis)
+ /// Time period for chargeback analysis
+ /// Cancellation token for async operation
+ /// Comprehensive chargeback analytics with risk mitigation recommendations
+ /// Thrown when parameters are invalid
+ /// Thrown when operation is cancelled
+ Task GetChargebackAnalyticsAsync(int? kingdomId, TimeSpan analysisTimeframe,
+ CancellationToken cancellationToken = default);
+
+ #endregion
+
+ #region Revenue Analytics and Optimization
+
+ ///
+ /// Gets comprehensive revenue analytics including total revenue, average transaction size,
+ /// conversion rates, player lifetime value, and revenue per user metrics for business intelligence.
+ ///
+ /// The kingdom to analyze (null for global analysis)
+ /// Time period for revenue analysis
+ /// Player segmentation criteria for detailed analysis
+ /// Cancellation token for async operation
+ /// Detailed revenue analytics with trends and optimization recommendations
+ /// Thrown when parameters are invalid
+ /// Thrown when operation is cancelled
+ Task GetRevenueAnalyticsAsync(int? kingdomId, TimeSpan analysisTimeframe,
+ object? segmentationCriteria = null, CancellationToken cancellationToken = default);
+
+ ///
+ /// Analyzes purchase conversion funnels to identify optimization opportunities including offer timing,
+ /// price points, product bundling effectiveness, and user experience friction points.
+ ///
+ /// Type of conversion funnel to analyze
+ /// The kingdom context for analysis
+ /// Time period for funnel analysis
+ /// Cancellation token for async operation
+ /// Conversion funnel analysis with optimization recommendations
+ /// Thrown when parameters are invalid
+ /// Thrown when operation is cancelled
+ Task AnalyzePurchaseConversionFunnelsAsync(string conversionFunnelType, int kingdomId,
+ TimeSpan analysisTimeframe, CancellationToken cancellationToken = default);
+
+ ///
+ /// Gets customer lifetime value predictions based on purchase history, engagement patterns,
+ /// VIP progression, and behavioral indicators for targeted marketing and retention strategies.
+ ///
+ /// The player to calculate LTV for (null for cohort analysis)
+ /// The kingdom context for calculations
+ /// Time horizon for LTV prediction
+ /// Cancellation token for async operation
+ /// LTV predictions with confidence intervals and contributing factors
+ /// Thrown when parameters are invalid
+ /// Thrown when operation is cancelled
+ Task CalculateCustomerLifetimeValueAsync(int? playerId, int kingdomId, TimeSpan predictionHorizon,
+ CancellationToken cancellationToken = default);
+
+ ///
+ /// Identifies revenue optimization opportunities including underperforming products, pricing adjustments,
+ /// bundle optimization, and promotional timing for maximizing sustainable revenue growth.
+ ///
+ /// Area to focus optimization on (pricing, products, timing, etc.)
+ /// The kingdom context for optimization
+ /// Time period for optimization analysis
+ /// Cancellation token for async operation
+ /// Revenue optimization recommendations with projected impact
+ /// Thrown when parameters are invalid
+ /// Thrown when operation is cancelled
+ Task IdentifyRevenueOptimizationOpportunitiesAsync(string optimizationFocus, int kingdomId,
+ TimeSpan analysisTimeframe, CancellationToken cancellationToken = default);
+
+ #endregion
+
+ #region Player Spending Patterns and Behavior
+
+ ///
+ /// Gets detailed player spending history including purchase frequency, preferred products, spending triggers,
+ /// and behavioral patterns for personalized offers and customer service optimization.
+ ///
+ /// The player to analyze spending patterns for
+ /// The kingdom context for analysis
+ /// Time period for spending pattern analysis
+ /// Cancellation token for async operation
+ /// Comprehensive spending pattern analysis with personalization recommendations
+ /// Thrown when parameters are invalid
+ /// Thrown when operation is cancelled
+ Task GetPlayerSpendingPatternsAsync(int playerId, int kingdomId, TimeSpan analysisTimeframe,
+ CancellationToken cancellationToken = default);
+
+ ///
+ /// Identifies players at risk of churn based on spending pattern changes, engagement decline,
+ /// and behavioral indicators for targeted retention campaigns and personalized re-engagement.
+ ///
+ /// The kingdom to analyze for churn risk
+ /// Risk threshold for churn prediction
+ /// Cancellation token for async operation
+ /// Players at risk of churn with risk factors and retention recommendations
+ /// Thrown when parameters are invalid
+ /// Thrown when operation is cancelled
+ Task>
+ IdentifyPlayersAtChurnRiskAsync(int kingdomId, double riskThreshold = 0.7,
+ CancellationToken cancellationToken = default);
+
+ ///
+ /// Analyzes spending triggers and motivations to understand what drives purchase decisions,
+ /// including competitive pressure, progression needs, social factors, and event participation.
+ ///
+ /// Specific purchases to analyze triggers for
+ /// The kingdom context for analysis
+ /// Cancellation token for async operation
+ /// Spending trigger analysis with motivation insights and optimization opportunities
+ /// Thrown when parameters are invalid
+ /// Thrown when operation is cancelled
+ Task AnalyzeSpendingTriggersAsync(IEnumerable purchaseLogIds, int kingdomId,
+ CancellationToken cancellationToken = default);
+
+ ///
+ /// Gets cohort analysis of player spending behavior over time, tracking how spending patterns
+ /// evolve based on registration date, first purchase timing, and progression milestones.
+ ///
+ /// How to define cohorts (registration month, first purchase, etc.)
+ /// The kingdom context for cohort analysis
+ /// Time period for cohort tracking
+ /// Cancellation token for async operation
+ /// Cohort spending analysis with lifecycle insights and optimization recommendations
+ /// Thrown when parameters are invalid
+ /// Thrown when operation is cancelled
+ Task GetSpendingCohortAnalysisAsync(string cohortDefinition, int kingdomId, TimeSpan analysisTimeframe,
+ CancellationToken cancellationToken = default);
+
+ #endregion
+
+ #region Anti-Pay-to-Win Balance Monitoring
+
+ ///
+ /// Monitors purchase impact on game balance to ensure spending provides value without creating
+ /// pay-to-win dominance. Tracks competitive balance metrics and player satisfaction indicators.
+ ///
+ /// The kingdom to monitor balance for
+ /// Time period for balance monitoring
+ /// Cancellation token for async operation
+ /// Game balance analysis with pay-to-win risk assessment and adjustment recommendations
+ /// Thrown when parameters are invalid
+ /// Thrown when operation is cancelled
+ Task MonitorPurchaseImpactOnGameBalanceAsync(int kingdomId, TimeSpan monitoringTimeframe,
+ CancellationToken cancellationToken = default);
+
+ ///
+ /// Analyzes effectiveness of skill-based alternatives to premium features, ensuring free-to-play
+ /// players can achieve competitive results through skill and time investment rather than spending.
+ ///
+ /// The skill-based alternative to analyze
+ /// The kingdom context for analysis
+ /// Time period for effectiveness analysis
+ /// Cancellation token for async operation
+ /// Skill-based alternative effectiveness with balance recommendations
+ /// Thrown when parameters are invalid
+ /// Thrown when operation is cancelled
+ Task AnalyzeSkillBasedAlternativeEffectivenessAsync(string skillBasedFeature, int kingdomId,
+ TimeSpan analysisTimeframe, CancellationToken cancellationToken = default);
+
+ ///
+ /// Gets competitive balance metrics comparing performance of paying vs non-paying players
+ /// to ensure spending enhances experience without creating unfair advantages or dominance.
+ ///
+ /// The kingdom to analyze competitive balance for
+ /// The metric to analyze (power, progression, success rate, etc.)
+ /// Time period for competitive analysis
+ /// Cancellation token for async operation
+ /// Competitive balance analysis with fairness assessment and adjustment recommendations
+ /// Thrown when parameters are invalid
+ /// Thrown when operation is cancelled
+ Task GetCompetitiveBalanceMetricsAsync(int kingdomId, string competitiveMetric,
+ TimeSpan analysisTimeframe, CancellationToken cancellationToken = default);
+
+ #endregion
+
+ #region Purchase History and Audit Trails
+
+ ///
+ /// Gets comprehensive purchase history for a player including all transactions, refunds, chargebacks,
+ /// VIP progression, and account adjustments for customer service and audit purposes.
+ ///
+ /// The player to get purchase history for
+ /// The kingdom context for the history
+ /// Whether to include refunded transactions
+ /// Cancellation token for async operation
+ /// Complete purchase history with transaction details and account impacts
+ /// Thrown when parameters are invalid
+ /// Thrown when operation is cancelled
+ Task> GetPlayerPurchaseHistoryAsync(int playerId, int kingdomId, bool includeRefunds = true,
+ CancellationToken cancellationToken = default);
+
+ ///
+ /// Gets purchase audit trail for financial compliance and investigation purposes including
+ /// all transaction modifications, admin actions, system adjustments, and verification records.
+ ///
+ /// The purchase to get audit trail for
+ /// The kingdom context for the audit
+ /// Cancellation token for async operation
+ /// Complete audit trail with chronological record of all purchase-related actions
+ /// Thrown when parameters are invalid
+ /// Thrown when operation is cancelled
+ Task GetPurchaseAuditTrailAsync(int purchaseLogId, int kingdomId,
+ CancellationToken cancellationToken = default);
+
+ ///
+ /// Generates financial compliance reports for regulatory requirements, tax reporting,
+ /// and internal audit purposes including revenue reconciliation and transaction verification.
+ ///
+ /// Type of compliance report to generate
+ /// Time period for the compliance report
+ /// Specific regulatory requirements to address
+ /// Cancellation token for async operation
+ /// Compliance report with required financial data and verification
+ /// Thrown when parameters are invalid
+ /// Thrown when operation is cancelled
+ Task GenerateComplianceReportAsync(string reportType, TimeSpan reportingPeriod,
+ object? jurisdictionRequirements = null, CancellationToken cancellationToken = default);
+
+ ///
+ /// Validates purchase data integrity by cross-referencing internal records with external payment
+ /// processor data, identifying discrepancies, and ensuring financial accuracy for audit purposes.
+ ///
+ /// Time period to validate purchase data for
+ /// External records for cross-reference
+ /// Cancellation token for async operation
+ /// Data integrity validation results with discrepancy identification and resolution
+ /// Thrown when parameters are invalid
+ /// Thrown when operation is cancelled
+ Task ValidatePurchaseDataIntegrityAsync(TimeSpan validationTimeframe,
+ object? paymentProcessorRecords = null, CancellationToken cancellationToken = default);
+
+ #endregion
+ }
+}
\ No newline at end of file
diff --git a/ShadowedRealmsMobile/src/server/ShadowedRealms.Core/Interfaces/Repositories/IRepository.cs b/ShadowedRealmsMobile/src/server/ShadowedRealms.Core/Interfaces/Repositories/IRepository.cs
new file mode 100644
index 0000000..80697a0
--- /dev/null
+++ b/ShadowedRealmsMobile/src/server/ShadowedRealms.Core/Interfaces/Repositories/IRepository.cs
@@ -0,0 +1,336 @@
+/*
+ * File: /src/server/ShadowedRealms.Core/Interfaces/Repositories/IRepository.cs
+ * Created: 2025-10-19
+ * Last Modified: 2025-10-19
+ * Description: Base repository interface defining common CRUD operations with kingdom-scoped data access patterns.
+ * All specific repository interfaces inherit from this to ensure consistent data access patterns
+ * and kingdom boundary enforcement across the entire application.
+ * Last Edit Notes: Initial implementation with comprehensive async operations, kingdom scoping, and error handling contracts.
+ */
+
+using System.Linq.Expressions;
+
+namespace ShadowedRealms.Core.Interfaces.Repositories
+{
+ ///
+ /// Base repository interface providing common CRUD operations with kingdom-scoped data access.
+ /// All entity repositories must inherit from this interface to ensure consistent data access patterns
+ /// and automatic kingdom boundary enforcement.
+ ///
+ /// The entity type that this repository manages
+ /// The primary key type for the entity
+ public interface IRepository where TEntity : class
+ {
+ #region Kingdom-Scoped Query Operations
+
+ ///
+ /// Gets an entity by its primary key within the specified kingdom context.
+ /// Automatically applies kingdom-scoped filtering to prevent cross-kingdom data access.
+ ///
+ /// The primary key of the entity to retrieve
+ /// The kingdom context for the query
+ /// Cancellation token for async operation
+ /// The entity if found within the kingdom, null otherwise
+ /// Thrown when kingdomId is invalid
+ /// Thrown when operation is cancelled
+ Task GetByIdAsync(TKey id, int kingdomId, CancellationToken cancellationToken = default);
+
+ ///
+ /// Gets an entity by its primary key with related entities included, within the specified kingdom context.
+ /// Automatically applies kingdom-scoped filtering to all included navigation properties.
+ ///
+ /// The primary key of the entity to retrieve
+ /// The kingdom context for the query
+ /// Navigation properties to include in the query
+ /// Cancellation token for async operation
+ /// The entity with included properties if found within the kingdom, null otherwise
+ /// Thrown when kingdomId is invalid or includeProperties contains invalid property names
+ /// Thrown when operation is cancelled
+ Task GetByIdWithIncludesAsync(TKey id, int kingdomId, CancellationToken cancellationToken = default,
+ params Expression>[] includeProperties);
+
+ ///
+ /// Gets all entities within the specified kingdom context.
+ /// Results are automatically filtered to prevent cross-kingdom data access.
+ ///
+ /// The kingdom context for the query
+ /// Cancellation token for async operation
+ /// All entities belonging to the specified kingdom
+ /// Thrown when kingdomId is invalid
+ /// Thrown when operation is cancelled
+ Task> GetAllAsync(int kingdomId, CancellationToken cancellationToken = default);
+
+ ///
+ /// Gets entities matching the specified predicate within the kingdom context.
+ /// The predicate is combined with kingdom-scoped filtering automatically.
+ ///
+ /// The condition to filter entities
+ /// The kingdom context for the query
+ /// Cancellation token for async operation
+ /// Entities matching the predicate within the specified kingdom
+ /// Thrown when predicate is null
+ /// Thrown when kingdomId is invalid
+ /// Thrown when operation is cancelled
+ Task> GetWhereAsync(Expression> predicate, int kingdomId,
+ CancellationToken cancellationToken = default);
+
+ ///
+ /// Gets entities matching the specified predicate with related entities included, within the kingdom context.
+ /// Both the predicate and includes are automatically kingdom-scoped.
+ ///
+ /// The condition to filter entities
+ /// The kingdom context for the query
+ /// Navigation properties to include in the query
+ /// Cancellation token for async operation
+ /// Entities matching the predicate with included properties within the specified kingdom
+ /// Thrown when predicate is null
+ /// Thrown when kingdomId is invalid or includeProperties contains invalid property names
+ /// Thrown when operation is cancelled
+ Task> GetWhereWithIncludesAsync(Expression> predicate, int kingdomId,
+ CancellationToken cancellationToken = default, params Expression>[] includeProperties);
+
+ ///
+ /// Gets the first entity matching the specified predicate within the kingdom context, or null if not found.
+ /// Automatically applies kingdom-scoped filtering.
+ ///
+ /// The condition to filter entities
+ /// The kingdom context for the query
+ /// Cancellation token for async operation
+ /// The first matching entity within the kingdom, or null if not found
+ /// Thrown when predicate is null
+ /// Thrown when kingdomId is invalid
+ /// Thrown when operation is cancelled
+ Task GetFirstOrDefaultAsync(Expression> predicate, int kingdomId,
+ CancellationToken cancellationToken = default);
+
+ #endregion
+
+ #region Paginated Query Operations
+
+ ///
+ /// Gets a paginated list of entities within the specified kingdom context.
+ /// Results are automatically kingdom-scoped and ordered for consistent pagination.
+ ///
+ /// The page number (1-based)
+ /// The number of entities per page
+ /// The kingdom context for the query
+ /// Cancellation token for async operation
+ /// Paginated results within the specified kingdom
+ /// Thrown when pageNumber or pageSize is invalid, or kingdomId is invalid
+ /// Thrown when operation is cancelled
+ Task<(IEnumerable Items, int TotalCount, int PageCount)> GetPagedAsync(int pageNumber, int pageSize,
+ int kingdomId, CancellationToken cancellationToken = default);
+
+ ///
+ /// Gets a paginated list of entities matching the specified predicate within the kingdom context.
+ /// Results are automatically kingdom-scoped and ordered for consistent pagination.
+ ///
+ /// The condition to filter entities
+ /// The page number (1-based)
+ /// The number of entities per page
+ /// The kingdom context for the query
+ /// Cancellation token for async operation
+ /// Paginated filtered results within the specified kingdom
+ /// Thrown when predicate is null
+ /// Thrown when pageNumber or pageSize is invalid, or kingdomId is invalid
+ /// Thrown when operation is cancelled
+ Task<(IEnumerable Items, int TotalCount, int PageCount)> GetPagedWhereAsync(
+ Expression> predicate, int pageNumber, int pageSize, int kingdomId,
+ CancellationToken cancellationToken = default);
+
+ #endregion
+
+ #region Count and Existence Operations
+
+ ///
+ /// Gets the count of all entities within the specified kingdom context.
+ /// Automatically applies kingdom-scoped filtering.
+ ///
+ /// The kingdom context for the query
+ /// Cancellation token for async operation
+ /// The count of entities within the specified kingdom
+ /// Thrown when kingdomId is invalid
+ /// Thrown when operation is cancelled
+ Task CountAsync(int kingdomId, CancellationToken cancellationToken = default);
+
+ ///
+ /// Gets the count of entities matching the specified predicate within the kingdom context.
+ /// The predicate is combined with kingdom-scoped filtering automatically.
+ ///
+ /// The condition to filter entities
+ /// The kingdom context for the query
+ /// Cancellation token for async operation
+ /// The count of matching entities within the specified kingdom
+ /// Thrown when predicate is null
+ /// Thrown when kingdomId is invalid
+ /// Thrown when operation is cancelled
+ Task CountWhereAsync(Expression> predicate, int kingdomId,
+ CancellationToken cancellationToken = default);
+
+ ///
+ /// Checks if any entity exists within the specified kingdom context.
+ /// Automatically applies kingdom-scoped filtering.
+ ///
+ /// The kingdom context for the query
+ /// Cancellation token for async operation
+ /// True if any entities exist within the kingdom, false otherwise
+ /// Thrown when kingdomId is invalid
+ /// Thrown when operation is cancelled
+ Task AnyAsync(int kingdomId, CancellationToken cancellationToken = default);
+
+ ///
+ /// Checks if any entity matching the specified predicate exists within the kingdom context.
+ /// The predicate is combined with kingdom-scoped filtering automatically.
+ ///
+ /// The condition to filter entities
+ /// The kingdom context for the query
+ /// Cancellation token for async operation
+ /// True if any matching entities exist within the kingdom, false otherwise
+ /// Thrown when predicate is null
+ /// Thrown when kingdomId is invalid
+ /// Thrown when operation is cancelled
+ Task AnyAsync(Expression> predicate, int kingdomId,
+ CancellationToken cancellationToken = default);
+
+ #endregion
+
+ #region Modification Operations
+
+ ///
+ /// Adds a new entity to the repository within the specified kingdom context.
+ /// The entity's kingdom association is automatically validated and enforced.
+ ///
+ /// The entity to add
+ /// The kingdom context for the operation
+ /// Cancellation token for async operation
+ /// The added entity with any generated values populated
+ /// Thrown when entity is null
+ /// Thrown when kingdomId is invalid or entity belongs to different kingdom
+ /// Thrown when entity violates business rules
+ /// Thrown when operation is cancelled
+ Task AddAsync(TEntity entity, int kingdomId, CancellationToken cancellationToken = default);
+
+ ///
+ /// Adds multiple entities to the repository within the specified kingdom context.
+ /// All entities' kingdom associations are automatically validated and enforced.
+ ///
+ /// The entities to add
+ /// The kingdom context for the operation
+ /// Cancellation token for async operation
+ /// The added entities with any generated values populated
+ /// Thrown when entities collection is null
+ /// Thrown when kingdomId is invalid or any entity belongs to different kingdom
+ /// Thrown when any entity violates business rules
+ /// Thrown when operation is cancelled
+ Task> AddRangeAsync(IEnumerable entities, int kingdomId,
+ CancellationToken cancellationToken = default);
+
+ ///
+ /// Updates an existing entity within the specified kingdom context.
+ /// The entity's kingdom association is validated to prevent cross-kingdom modifications.
+ ///
+ /// The entity to update
+ /// The kingdom context for the operation
+ /// Cancellation token for async operation
+ /// The updated entity
+ /// Thrown when entity is null
+ /// Thrown when kingdomId is invalid or entity belongs to different kingdom
+ /// Thrown when entity doesn't exist or violates business rules
+ /// Thrown when operation is cancelled
+ Task UpdateAsync(TEntity entity, int kingdomId, CancellationToken cancellationToken = default);
+
+ ///
+ /// Updates multiple entities within the specified kingdom context.
+ /// All entities' kingdom associations are validated to prevent cross-kingdom modifications.
+ ///
+ /// The entities to update
+ /// The kingdom context for the operation
+ /// Cancellation token for async operation
+ /// The updated entities
+ /// Thrown when entities collection is null
+ /// Thrown when kingdomId is invalid or any entity belongs to different kingdom
+ /// Thrown when any entity doesn't exist or violates business rules
+ /// Thrown when operation is cancelled
+ Task> UpdateRangeAsync(IEnumerable entities, int kingdomId,
+ CancellationToken cancellationToken = default);
+
+ ///
+ /// Deletes an entity by its primary key within the specified kingdom context.
+ /// Automatically validates kingdom association before deletion.
+ ///
+ /// The primary key of the entity to delete
+ /// The kingdom context for the operation
+ /// Cancellation token for async operation
+ /// True if the entity was deleted, false if not found
+ /// Thrown when kingdomId is invalid
+ /// Thrown when entity cannot be deleted due to business rules
+ /// Thrown when operation is cancelled
+ Task DeleteAsync(TKey id, int kingdomId, CancellationToken cancellationToken = default);
+
+ ///
+ /// Deletes an entity within the specified kingdom context.
+ /// Automatically validates kingdom association before deletion.
+ ///
+ /// The entity to delete
+ /// The kingdom context for the operation
+ /// Cancellation token for async operation
+ /// True if the entity was deleted, false if not found
+ /// Thrown when entity is null
+ /// Thrown when kingdomId is invalid or entity belongs to different kingdom
+ /// Thrown when entity cannot be deleted due to business rules
+ /// Thrown when operation is cancelled
+ Task DeleteAsync(TEntity entity, int kingdomId, CancellationToken cancellationToken = default);
+
+ ///
+ /// Deletes entities matching the specified predicate within the kingdom context.
+ /// The predicate is combined with kingdom-scoped filtering automatically.
+ ///
+ /// The condition to filter entities for deletion
+ /// The kingdom context for the operation
+ /// Cancellation token for async operation
+ /// The number of entities deleted
+ /// Thrown when predicate is null
+ /// Thrown when kingdomId is invalid
+ /// Thrown when entities cannot be deleted due to business rules
+ /// Thrown when operation is cancelled
+ Task DeleteWhereAsync(Expression> predicate, int kingdomId,
+ CancellationToken cancellationToken = default);
+
+ #endregion
+
+ #region Transaction and Performance Operations
+
+ ///
+ /// Executes a database operation within a transaction scope, automatically handling rollback on exceptions.
+ /// All operations within the transaction maintain kingdom-scoped security.
+ ///
+ /// The return type of the operation
+ /// The operation to execute within the transaction
+ /// The kingdom context for the transaction
+ /// Cancellation token for async operation
+ /// The result of the operation
+ /// Thrown when operation is null
+ /// Thrown when kingdomId is invalid
+ /// Thrown when transaction fails
+ /// Thrown when operation is cancelled
+ Task ExecuteInTransactionAsync(Func> operation, int kingdomId,
+ CancellationToken cancellationToken = default);
+
+ ///
+ /// Executes a raw SQL query with parameters, automatically applying kingdom-scoped filtering.
+ /// Use only when LINQ queries are insufficient for performance or complexity requirements.
+ ///
+ /// The SQL query with parameter placeholders
+ /// The kingdom context for the query
+ /// The parameters for the SQL query
+ /// Cancellation token for async operation
+ /// Entities returned by the SQL query within the kingdom context
+ /// Thrown when sql is null/empty or kingdomId is invalid
+ /// Thrown when SQL execution fails
+ /// Thrown when operation is cancelled
+ Task> ExecuteRawSqlAsync(string sql, int kingdomId,
+ CancellationToken cancellationToken = default, params object[] parameters);
+
+ #endregion
+ }
+}
\ No newline at end of file