/*
 * File: D:\shadowed-realms-mobile\ShadowedRealmsMobile\src\server\ShadowedRealms.Core\Interfaces\Services\IPurchaseService.cs
 * Created: 2025-10-19
 * Last Modified: 2025-10-19
 * Description: Purchase service interface for coordinating monetization-related business logic operations including anti-pay-to-win monitoring, VIP progression management, spending balance validation, and skill-based alternative systems
 * Last Edit Notes: Initial creation with comprehensive anti-pay-to-win and balanced monetization operations
 */

using ShadowedRealms.Core.Models;

namespace ShadowedRealms.Core.Interfaces.Services
{
    /// <summary>
    /// Service interface for purchase and monetization-related business logic operations
    /// Implements anti-pay-to-win monitoring, balanced VIP progression, spending validation, and skill-based alternatives
    /// </summary>
    public interface IPurchaseService
    {
        #region Purchase Processing & Validation

        /// <summary>
        /// Processes player purchase with comprehensive validation, fraud detection, and balance monitoring
        /// Ensures all purchases maintain game balance and provide genuine value to players
        /// </summary>
        /// <param name="playerId">Player making the purchase</param>
        /// <param name="kingdomId">Kingdom scope for security</param>
        /// <param name="purchaseDetails">Details of the purchase including items and amounts</param>
        /// <param name="paymentMethod">Payment method and transaction details</param>
        /// <returns>Purchase processing result with validation status and applied benefits</returns>
        /// <exception cref="InvalidOperationException">Thrown when purchase validation fails</exception>
        Task<(bool Success, string TransactionId, Dictionary<string, object> AppliedBenefits,
               Dictionary<string, object> BalanceValidation)>
            ProcessPurchaseAsync(int playerId, int kingdomId, Dictionary<string, object> purchaseDetails,
                Dictionary<string, object> paymentMethod);

        /// <summary>
        /// Validates purchase for game balance impact and anti-pay-to-win compliance
        /// Prevents purchases that would create unfair advantages or disrupt competitive balance
        /// </summary>
        /// <param name="playerId">Player attempting purchase</param>
        /// <param name="kingdomId">Kingdom scope for security</param>
        /// <param name="purchaseDetails">Details of intended purchase</param>
        /// <returns>Purchase validation result with balance assessment and recommendations</returns>
        Task<(bool IsValid, List<string> ValidationWarnings, Dictionary<string, object> BalanceImpact,
               Dictionary<string, object> AlternativeOptions)>
            ValidatePurchaseBalanceAsync(int playerId, int kingdomId, Dictionary<string, object> purchaseDetails);

        /// <summary>
        /// Processes purchase refunds and chargebacks with appropriate game state adjustments
        /// Handles refund scenarios while maintaining game integrity and preventing abuse
        /// </summary>
        /// <param name="playerId">Player requesting refund</param>
        /// <param name="kingdomId">Kingdom scope for security</param>
        /// <param name="transactionId">Original transaction to refund</param>
        /// <param name="refundReason">Reason for refund request</param>
        /// <param name="refundType">Type of refund (voluntary, chargeback, dispute)</param>
        /// <returns>Refund processing result with game state adjustments and fraud prevention measures</returns>
        Task<(bool Success, Dictionary<string, object> StateAdjustments, Dictionary<string, object> FraudPrevention)>
            ProcessRefundAsync(int playerId, int kingdomId, string transactionId, string refundReason, string refundType);

        /// <summary>
        /// Detects and prevents purchase fraud including account manipulation and payment abuse
        /// </summary>
        /// <param name="playerId">Player making purchase</param>
        /// <param name="kingdomId">Kingdom scope for security</param>
        /// <param name="purchaseDetails">Purchase details for fraud analysis</param>
        /// <param name="paymentMethod">Payment method details for validation</param>
        /// <returns>Fraud detection result with risk assessment and prevention measures</returns>
        Task<(bool IsFraudulent, double RiskScore, List<string> FraudIndicators, Dictionary<string, object> PreventionMeasures)>
            DetectPurchaseFraudAsync(int playerId, int kingdomId, Dictionary<string, object> purchaseDetails,
                Dictionary<string, object> paymentMethod);

        #endregion

        #region Anti-Pay-to-Win Monitoring

        /// <summary>
        /// Monitors spending patterns for pay-to-win dominance and implements balance corrections
        /// Ensures competitive integrity by preventing spending from overwhelming skill-based gameplay
        /// </summary>
        /// <param name="playerId">Player to monitor spending patterns for</param>
        /// <param name="kingdomId">Kingdom scope for security</param>
        /// <param name="monitoringPeriod">Time period for spending analysis</param>
        /// <returns>Spending monitoring result with dominance assessment and balance recommendations</returns>
        Task<Dictionary<string, object>> MonitorPayToWinDominanceAsync(int playerId, int kingdomId,
            TimeSpan monitoringPeriod);

        /// <summary>
        /// Calculates competitive effectiveness ratio ensuring free players can achieve 70% effectiveness through skill
        /// Validates that skill-based play remains viable against spending advantages
        /// </summary>
        /// <param name="playerId">Player to analyze effectiveness for</param>
        /// <param name="kingdomId">Kingdom scope for security</param>
        /// <param name="comparisonGroup">Group of players for comparative analysis</param>
        /// <returns>Effectiveness analysis with skill vs spending breakdown and balance validation</returns>
        Task<Dictionary<string, object>> CalculateCompetitiveEffectivenessAsync(int playerId, int kingdomId,
            List<int> comparisonGroup);

        /// <summary>
        /// Implements dynamic balance adjustments to counter pay-to-win dominance
        /// Applies skill-based bonuses and strategic advantages to maintain competitive balance
        /// </summary>
        /// <param name="affectedPlayers">Players requiring balance adjustments</param>
        /// <param name="kingdomId">Kingdom scope for security</param>
        /// <param name="balanceType">Type of balance adjustment needed</param>
        /// <param name="adjustmentParameters">Parameters for balance calculations</param>
        /// <returns>Balance adjustment result with applied compensations and effectiveness validation</returns>
        Task<Dictionary<string, object>> ImplementBalanceAdjustmentsAsync(List<int> affectedPlayers, int kingdomId,
            string balanceType, Dictionary<string, object> adjustmentParameters);

        /// <summary>
        /// Validates that less than 30% of victory outcomes are determined purely by spending
        /// Monitors competitive integrity across different game modes and scenarios
        /// </summary>
        /// <param name="kingdomId">Kingdom to analyze victory patterns for</param>
        /// <param name="analysisTimeframe">Period to analyze victory outcomes</param>
        /// <param name="gameMode">Specific game mode to analyze (optional)</param>
        /// <returns>Victory outcome analysis with spending influence assessment and balance status</returns>
        Task<Dictionary<string, object>> ValidateVictoryOutcomeBalanceAsync(int kingdomId, TimeSpan analysisTimeframe,
            string gameMode = null);

        #endregion

        #region VIP System Management

        /// <summary>
        /// Manages VIP tier progression with secret tier handling and chargeback protection
        /// Implements graduated benefits that provide value without creating unfair advantages
        /// </summary>
        /// <param name="playerId">Player to manage VIP progression for</param>
        /// <param name="kingdomId">Kingdom scope for security</param>
        /// <param name="purchaseAmount">Purchase amount contributing to VIP progress</param>
        /// <param name="purchaseType">Type of purchase for VIP calculation</param>
        /// <returns>VIP progression result with tier updates, benefits, and chargeback risk assessment</returns>
        Task<(bool TierAdvanced, int NewVipTier, bool IsSecretTier, Dictionary<string, object> NewBenefits,
               double ChargebackRisk, Dictionary<string, object> SkillAlternatives)>
            ManageVipProgressionAsync(int playerId, int kingdomId, decimal purchaseAmount, string purchaseType);

        /// <summary>
        /// Calculates VIP benefits with built-in skill-based alternatives for non-VIP players
        /// Ensures VIP provides convenience and cosmetic benefits rather than gameplay advantages
        /// </summary>
        /// <param name="playerId">Player to calculate VIP benefits for</param>
        /// <param name="kingdomId">Kingdom scope for security</param>
        /// <param name="vipTier">VIP tier to calculate benefits for</param>
        /// <returns>VIP benefit calculation with skill-based alternatives and balance validation</returns>
        Task<Dictionary<string, object>> CalculateVipBenefitsWithAlternativesAsync(int playerId, int kingdomId, int vipTier);

        /// <summary>
        /// Processes VIP benefit claims with validation and anti-abuse measures
        /// Prevents exploitation of VIP systems while ensuring legitimate benefits are applied
        /// </summary>
        /// <param name="playerId">Player claiming VIP benefits</param>
        /// <param name="kingdomId">Kingdom scope for security</param>
        /// <param name="benefitType">Type of VIP benefit being claimed</param>
        /// <param name="claimParameters">Parameters for benefit claim</param>
        /// <returns>Benefit claim result with validation status and applied benefits</returns>
        Task<(bool Success, Dictionary<string, object> AppliedBenefits, List<string> ValidationWarnings)>
            ProcessVipBenefitClaimAsync(int playerId, int kingdomId, string benefitType,
                Dictionary<string, object> claimParameters);

        /// <summary>
        /// Manages chargeback protection for VIP tiers with appropriate game state adjustments
        /// Handles chargeback scenarios while maintaining VIP tier integrity
        /// </summary>
        /// <param name="playerId">Player with chargeback activity</param>
        /// <param name="kingdomId">Kingdom scope for security</param>
        /// <param name="chargebackDetails">Details of chargeback activity</param>
        /// <returns>Chargeback handling result with tier adjustments and protection measures</returns>
        Task<Dictionary<string, object>> HandleVipChargebackProtectionAsync(int playerId, int kingdomId,
            Dictionary<string, object> chargebackDetails);

        #endregion

        #region Skill-Based Alternative Systems

        /// <summary>
        /// Provides skill-based alternatives to premium features ensuring competitive viability for free players
        /// Implements achievement-based unlocks and strategic gameplay rewards
        /// </summary>
        /// <param name="playerId">Player to provide alternatives for</param>
        /// <param name="kingdomId">Kingdom scope for security</param>
        /// <param name="premiumFeature">Premium feature to provide alternatives for</param>
        /// <returns>Skill-based alternatives with achievement paths and strategic options</returns>
        Task<Dictionary<string, object>> ProvideSkillBasedAlternativesAsync(int playerId, int kingdomId,
            string premiumFeature);

        /// <summary>
        /// Calculates achievement-based rewards that provide competitive alternatives to spending
        /// Ensures skilled gameplay is recognized and rewarded appropriately
        /// </summary>
        /// <param name="playerId">Player to calculate achievement rewards for</param>
        /// <param name="kingdomId">Kingdom scope for security</param>
        /// <param name="achievementCategory">Category of achievements to analyze</param>
        /// <param name="timeframeDays">Period to analyze achievements over</param>
        /// <returns>Achievement-based rewards with competitive value assessment</returns>
        Task<Dictionary<string, object>> CalculateAchievementBasedRewardsAsync(int playerId, int kingdomId,
            string achievementCategory, int timeframeDays = 30);

        /// <summary>
        /// Implements strategic coordination bonuses that reward teamwork and skill over individual spending
        /// Promotes alliance cooperation and tactical gameplay
        /// </summary>
        /// <param name="playerId">Player participating in strategic coordination</param>
        /// <param name="allianceId">Alliance coordinating strategy</param>
        /// <param name="kingdomId">Kingdom scope for security</param>
        /// <param name="coordinationType">Type of strategic coordination</param>
        /// <param name="participationData">Data on player participation and effectiveness</param>
        /// <returns>Coordination bonuses with skill-based rewards and team effectiveness boosts</returns>
        Task<Dictionary<string, object>> ImplementStrategicCoordinationBonusesAsync(int playerId, int allianceId,
            int kingdomId, string coordinationType, Dictionary<string, object> participationData);

        /// <summary>
        /// Validates that skill-based alternatives provide meaningful competitive options
        /// Ensures balance between premium convenience and skill-based achievement
        /// </summary>
        /// <param name="kingdomId">Kingdom to validate alternatives for</param>
        /// <param name="alternativeType">Type of skill-based alternative to validate</param>
        /// <param name="validationCriteria">Criteria for alternative effectiveness</param>
        /// <returns>Alternative validation with effectiveness assessment and improvement recommendations</returns>
        Task<Dictionary<string, object>> ValidateSkillBasedAlternativeEffectivenessAsync(int kingdomId,
            string alternativeType, Dictionary<string, object> validationCriteria);

        #endregion

        #region Spending Analytics & Insights

        /// <summary>
        /// Generates comprehensive spending analytics for player behavior analysis and balance monitoring
        /// Provides insights for maintaining healthy monetization while preserving competitive integrity
        /// </summary>
        /// <param name="playerId">Player to analyze spending for</param>
        /// <param name="kingdomId">Kingdom scope for security</param>
        /// <param name="analysisType">Type of spending analysis to perform</param>
        /// <param name="timeframeDays">Period to analyze spending over</param>
        /// <returns>Comprehensive spending analytics with behavior patterns and balance insights</returns>
        Task<Dictionary<string, object>> GenerateSpendingAnalyticsAsync(int playerId, int kingdomId,
            string analysisType, int timeframeDays = 30);

        /// <summary>
        /// Analyzes kingdom-wide spending patterns for balance monitoring and health assessment
        /// Identifies spending concentration and competitive balance issues
        /// </summary>
        /// <param name="kingdomId">Kingdom to analyze spending patterns for</param>
        /// <param name="analysisDepth">Depth of analysis to perform</param>
        /// <returns>Kingdom spending analysis with balance assessment and health indicators</returns>
        Task<Dictionary<string, object>> AnalyzeKingdomSpendingPatternsAsync(int kingdomId, string analysisDepth);

        /// <summary>
        /// Calculates player lifetime value with ethical monetization considerations
        /// Balances revenue optimization with player satisfaction and retention
        /// </summary>
        /// <param name="playerId">Player to calculate lifetime value for</param>
        /// <param name="kingdomId">Kingdom scope for security</param>
        /// <param name="projectionMonths">Months to project lifetime value over</param>
        /// <returns>Lifetime value calculation with ethical monetization recommendations</returns>
        Task<Dictionary<string, object>> CalculatePlayerLifetimeValueAsync(int playerId, int kingdomId,
            int projectionMonths = 12);

        /// <summary>
        /// Monitors monetization health metrics ensuring sustainable and ethical revenue generation
        /// Tracks player satisfaction, retention, and competitive balance alongside revenue metrics
        /// </summary>
        /// <param name="kingdomId">Kingdom to monitor monetization health for</param>
        /// <param name="healthMetrics">Specific health metrics to analyze</param>
        /// <returns>Monetization health assessment with sustainability recommendations</returns>
        Task<Dictionary<string, object>> MonitorMonetizationHealthAsync(int kingdomId, List<string> healthMetrics);

        #endregion

        #region Purchase Recommendations & Optimization

        /// <summary>
        /// Provides ethical purchase recommendations that genuinely benefit players without creating unfair advantages
        /// Focuses on convenience, cosmetic, and quality-of-life improvements
        /// </summary>
        /// <param name="playerId">Player to provide recommendations for</param>
        /// <param name="kingdomId">Kingdom scope for security</param>
        /// <param name="playerPreferences">Player preferences and gameplay patterns</param>
        /// <returns>Ethical purchase recommendations with genuine value assessment</returns>
        Task<Dictionary<string, object>> ProvideEthicalPurchaseRecommendationsAsync(int playerId, int kingdomId,
            Dictionary<string, object> playerPreferences);

        /// <summary>
        /// Optimizes purchase timing and value to maximize player satisfaction while maintaining balance
        /// Prevents aggressive monetization tactics that could harm player experience
        /// </summary>
        /// <param name="playerId">Player to optimize purchases for</param>
        /// <param name="kingdomId">Kingdom scope for security</param>
        /// <param name="purchaseHistory">Player's purchase history and patterns</param>
        /// <returns>Purchase optimization with player-first recommendations and value maximization</returns>
        Task<Dictionary<string, object>> OptimizePurchaseValueAsync(int playerId, int kingdomId,
            Dictionary<string, object> purchaseHistory);

        /// <summary>
        /// Implements spending caps and healthy monetization limits to prevent excessive spending
        /// Protects players from harmful spending patterns while maintaining business viability
        /// </summary>
        /// <param name="playerId">Player to manage spending limits for</param>
        /// <param name="kingdomId">Kingdom scope for security</param>
        /// <param name="spendingData">Current spending patterns and history</param>
        /// <param name="limitParameters">Parameters for spending limit calculation</param>
        /// <returns>Spending limit management with player protection measures and healthy spending guidance</returns>
        Task<(bool LimitsApplied, Dictionary<string, object> SpendingLimits, Dictionary<string, object> HealthGuidance)>
            ManageHealthySpendingLimitsAsync(int playerId, int kingdomId, Dictionary<string, object> spendingData,
                Dictionary<string, object> limitParameters);

        #endregion

        #region Transaction Security & Compliance

        /// <summary>
        /// Validates transaction security and compliance with platform requirements and regulations
        /// Ensures all transactions meet legal and platform compliance standards
        /// </summary>
        /// <param name="transactionDetails">Details of transaction to validate</param>
        /// <param name="complianceRequirements">Applicable compliance requirements</param>
        /// <returns>Transaction compliance validation with security assessment and regulatory compliance status</returns>
        Task<(bool IsCompliant, List<string> ComplianceIssues, Dictionary<string, object> SecurityAssessment)>
            ValidateTransactionComplianceAsync(Dictionary<string, object> transactionDetails,
                Dictionary<string, object> complianceRequirements);

        /// <summary>
        /// Processes payment security verification with fraud prevention and risk assessment
        /// Implements comprehensive security measures to protect against payment fraud
        /// </summary>
        /// <param name="paymentDetails">Payment information to verify</param>
        /// <param name="playerVerification">Player identity verification data</param>
        /// <returns>Payment security verification with fraud risk assessment and verification status</returns>
        Task<(bool IsSecure, double FraudRisk, Dictionary<string, object> SecurityChecks)>
            VerifyPaymentSecurityAsync(Dictionary<string, object> paymentDetails,
                Dictionary<string, object> playerVerification);

        /// <summary>
        /// Manages transaction audit trails for compliance and dispute resolution
        /// Maintains comprehensive records for regulatory compliance and player protection
        /// </summary>
        /// <param name="transactionId">Transaction to create audit trail for</param>
        /// <param name="auditDetails">Details to include in audit trail</param>
        /// <returns>Audit trail creation result with compliance record and dispute prevention measures</returns>
        Task<Dictionary<string, object>> CreateTransactionAuditTrailAsync(string transactionId,
            Dictionary<string, object> auditDetails);

        #endregion

        #region Purchase History & Player Protection

        /// <summary>
        /// Retrieves comprehensive purchase history with privacy protection and dispute support
        /// Provides transparent purchase records while protecting sensitive payment information
        /// </summary>
        /// <param name="playerId">Player to retrieve purchase history for</param>
        /// <param name="kingdomId">Kingdom scope for security</param>
        /// <param name="timeframeDays">Period to retrieve history for</param>
        /// <param name="includeDetails">Whether to include detailed transaction information</param>
        /// <returns>Purchase history with privacy-protected details and dispute support information</returns>
        Task<Dictionary<string, object>> GetPurchaseHistoryAsync(int playerId, int kingdomId, int timeframeDays = 90,
            bool includeDetails = false);

        /// <summary>
        /// Provides purchase dispute resolution support with fair and transparent processes
        /// Handles player concerns and disputes with appropriate resolution mechanisms
        /// </summary>
        /// <param name="playerId">Player raising dispute</param>
        /// <param name="kingdomId">Kingdom scope for security</param>
        /// <param name="disputeDetails">Details of the dispute</param>
        /// <param name="disputeType">Type of dispute being raised</param>
        /// <returns>Dispute resolution result with investigation findings and resolution actions</returns>
        Task<(bool DisputeResolved, Dictionary<string, object> ResolutionActions, Dictionary<string, object> InvestigationFindings)>
            ProcessPurchaseDisputeAsync(int playerId, int kingdomId, Dictionary<string, object> disputeDetails,
                string disputeType);

        /// <summary>
        /// Implements player protection measures for vulnerable spending patterns
        /// Identifies and supports players who may need protection from excessive spending
        /// </summary>
        /// <param name="playerId">Player to assess protection needs for</param>
        /// <param name="kingdomId">Kingdom scope for security</param>
        /// <param name="spendingPattern">Player's spending behavior and patterns</param>
        /// <returns>Player protection assessment with support measures and intervention recommendations</returns>
        Task<Dictionary<string, object>> AssessPlayerProtectionNeedsAsync(int playerId, int kingdomId,
            Dictionary<string, object> spendingPattern);

        #endregion

        #region Revenue Analytics & Business Intelligence

        /// <summary>
        /// Generates ethical revenue analytics that balance business goals with player welfare
        /// Provides insights for sustainable monetization strategies
        /// </summary>
        /// <param name="kingdomIds">Kingdoms to analyze revenue for</param>
        /// <param name="analysisType">Type of revenue analysis to perform</param>
        /// <param name="timeframeDays">Period to analyze revenue over</param>
        /// <returns>Revenue analytics with ethical monetization insights and sustainability recommendations</returns>
        Task<Dictionary<string, object>> GenerateEthicalRevenueAnalyticsAsync(List<int> kingdomIds, string analysisType,
            int timeframeDays = 30);

        /// <summary>
        /// Analyzes purchase conversion patterns with player satisfaction correlation
        /// Identifies conversion opportunities that genuinely benefit players
        /// </summary>
        /// <param name="kingdomId">Kingdom to analyze conversion patterns for</param>
        /// <param name="conversionType">Type of conversion to analyze</param>
        /// <returns>Conversion analysis with player satisfaction correlation and ethical improvement recommendations</returns>
        Task<Dictionary<string, object>> AnalyzePurchaseConversionPatternsAsync(int kingdomId, string conversionType);

        /// <summary>
        /// Calculates sustainable monetization metrics that prioritize long-term player value
        /// Balances revenue goals with player retention and satisfaction
        /// </summary>
        /// <param name="kingdomIds">Kingdoms to calculate metrics for</param>
        /// <param name="sustainabilityFactors">Factors to consider in sustainability calculation</param>
        /// <returns>Sustainable monetization metrics with long-term viability assessment</returns>
        Task<Dictionary<string, object>> CalculateSustainableMonetizationMetricsAsync(List<int> kingdomIds,
            Dictionary<string, object> sustainabilityFactors);

        #endregion
    }
}