/*
 * File: D:\shadowed-realms-mobile\ShadowedRealmsMobile\src\server\ShadowedRealms.API\Controllers\Purchase\PurchaseController.cs
 * Created: 2025-10-19
 * Last Modified: 2025-10-26
 * Description: REST API controller for purchase operations including ethical monetization, anti-pay-to-win monitoring,
 *              VIP progression, and skill-based alternatives with comprehensive player protection systems.
 * Last Edit Notes: Fixed all method signature mismatches with IPurchaseService interface
 */

using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using ShadowedRealms.Core.Interfaces.Services;
using System.Security.Claims;
using System.Text.Json;

namespace ShadowedRealms.API.Controllers.Purchase
{
    /// <summary>
    /// REST API controller for ethical monetization and purchase operations
    /// </summary>
    [ApiController]
    [Route("api/v1/purchases")]
    [Authorize] // JWT authentication required for all purchase operations
    [Produces("application/json")]
    public class PurchaseController : ControllerBase
    {
        private readonly IPurchaseService _purchaseService;
        private readonly ILogger<PurchaseController> _logger;

        public PurchaseController(
            IPurchaseService purchaseService,
            ILogger<PurchaseController> logger)
        {
            _purchaseService = purchaseService ?? throw new ArgumentNullException(nameof(purchaseService));
            _logger = logger ?? throw new ArgumentNullException(nameof(logger));
        }

        #region Purchase Processing

        /// <summary>
        /// Processes purchase with comprehensive fraud detection and balance validation
        /// </summary>
        /// <param name="request">Purchase processing parameters</param>
        /// <returns>Purchase processing result with fraud analysis and balance impact</returns>
        [HttpPost("process")]
        [ProducesResponseType(typeof(object), 200)]
        [ProducesResponseType(400)]
        [ProducesResponseType(409)] // Purchase blocked due to fraud or balance concerns
        public async Task<IActionResult> ProcessPurchase([FromBody] object request)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return BadRequest(new { Message = "Invalid purchase request", Code = "INVALID_REQUEST" });
                }

                var (playerId, kingdomId) = GetAuthenticatedPlayer();
                var requestDict = System.Text.Json.JsonSerializer.Deserialize<Dictionary<string, object>>(request.ToString() ?? "{}");

                var purchaseAmount = requestDict?.ContainsKey("purchaseAmount") == true ?
                    Convert.ToDecimal(requestDict["purchaseAmount"]) : 0m;
                var packageId = requestDict?.ContainsKey("packageId") == true ?
                    requestDict["packageId"].ToString() : "";
                var paymentDetails = requestDict?.ContainsKey("paymentDetails") == true ?
                    (Dictionary<string, object>)requestDict["paymentDetails"] : new();

                var purchaseDetails = new Dictionary<string, object>
                {
                    ["purchaseAmount"] = purchaseAmount,
                    ["packageId"] = packageId
                };

                var (success, transactionId, appliedBenefits, balanceValidation) =
                    await _purchaseService.ProcessPurchaseAsync(
                        playerId, kingdomId, purchaseDetails, paymentDetails);

                if (!success)
                {
                    var blockingReason = balanceValidation?.ContainsKey("blocked") == true ? "Balance protection" :
                                        "Purchase validation failed";

                    return Conflict(new
                    {
                        Message = $"Purchase blocked - {blockingReason}",
                        Code = "PURCHASE_BLOCKED",
                        Details = new
                        {
                            AppliedBenefits = appliedBenefits,
                            BalanceValidation = balanceValidation
                        }
                    });
                }

                var response = new
                {
                    PlayerId = playerId,
                    Success = success,
                    TransactionId = transactionId,
                    PurchaseAmount = purchaseAmount,
                    PackageId = packageId,
                    AppliedBenefits = appliedBenefits,
                    BalanceValidation = balanceValidation,
                    ProcessingTime = DateTime.UtcNow
                };

                _logger.LogInformation("Purchase processed successfully for Player {PlayerId} - Transaction: {TransactionId}, Amount: {Amount}",
                    playerId, transactionId, purchaseAmount);

                return Ok(response);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error processing purchase for Player {PlayerId}", GetAuthenticatedPlayer().PlayerId);
                return StatusCode(500, new { Message = "Failed to process purchase", Code = "PURCHASE_PROCESSING_ERROR" });
            }
        }

        /// <summary>
        /// Validates purchase against fraud detection and spending limits
        /// </summary>
        /// <param name="request">Purchase validation parameters</param>
        /// <returns>Purchase validation result with risk assessment</returns>
        [HttpPost("validate")]
        [ProducesResponseType(typeof(object), 200)]
        [ProducesResponseType(400)]
        public async Task<IActionResult> ValidatePurchase([FromBody] object request)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return BadRequest(new { Message = "Invalid purchase validation request", Code = "INVALID_REQUEST" });
                }

                var (playerId, kingdomId) = GetAuthenticatedPlayer();
                var requestDict = System.Text.Json.JsonSerializer.Deserialize<Dictionary<string, object>>(request.ToString() ?? "{}");

                var purchaseAmount = requestDict?.ContainsKey("purchaseAmount") == true ?
                    Convert.ToDecimal(requestDict["purchaseAmount"]) : 0m;
                var packageId = requestDict?.ContainsKey("packageId") == true ?
                    requestDict["packageId"].ToString() : "";
                var validationType = requestDict?.ContainsKey("validationType") == true ?
                    requestDict["validationType"].ToString() : "comprehensive";

                var purchaseDetails = new Dictionary<string, object>
                {
                    ["purchaseAmount"] = purchaseAmount,
                    ["packageId"] = packageId,
                    ["validationType"] = validationType
                };

                var (isValid, validationWarnings, balanceImpact, alternativeOptions) =
                    await _purchaseService.ValidatePurchaseBalanceAsync(
                        playerId, kingdomId, purchaseDetails);

                var response = new
                {
                    PlayerId = playerId,
                    PurchaseAmount = purchaseAmount,
                    PackageId = packageId,
                    IsValid = isValid,
                    ValidationWarnings = validationWarnings,
                    BalanceImpact = balanceImpact,
                    AlternativeOptions = alternativeOptions,
                    ValidationTime = DateTime.UtcNow
                };

                return Ok(response);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error validating purchase for Player {PlayerId}", GetAuthenticatedPlayer().PlayerId);
                return StatusCode(500, new { Message = "Failed to validate purchase", Code = "PURCHASE_VALIDATION_ERROR" });
            }
        }

        /// <summary>
        /// Processes purchase refund with game state adjustments
        /// </summary>
        /// <param name="transactionId">Transaction to refund</param>
        /// <param name="request">Refund processing parameters</param>
        /// <returns>Refund processing result with state adjustments</returns>
        [HttpPost("{transactionId}/refund")]
        [ProducesResponseType(typeof(object), 200)]
        [ProducesResponseType(400)]
        [ProducesResponseType(404)] // Transaction not found
        public async Task<IActionResult> ProcessRefund(string transactionId, [FromBody] object request)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return BadRequest(new { Message = "Invalid refund request", Code = "INVALID_REQUEST" });
                }

                var (playerId, kingdomId) = GetAuthenticatedPlayer();
                var requestDict = System.Text.Json.JsonSerializer.Deserialize<Dictionary<string, object>>(request.ToString() ?? "{}");

                var refundReason = requestDict?.ContainsKey("refundReason") == true ?
                    requestDict["refundReason"].ToString() : "";
                var refundAmount = requestDict?.ContainsKey("refundAmount") == true ?
                    Convert.ToDecimal(requestDict["refundAmount"]) : 0m;

                var (success, stateAdjustments, fraudPrevention) =
                    await _purchaseService.ProcessRefundAsync(
                        playerId, kingdomId, transactionId, refundReason, "voluntary");

                if (!success)
                {
                    return NotFound(new { Message = "Transaction not found or refund not allowed", Code = "REFUND_FAILED" });
                }

                var response = new
                {
                    PlayerId = playerId,
                    TransactionId = transactionId,
                    Success = success,
                    RefundAmount = refundAmount,
                    RefundReason = refundReason,
                    StateAdjustments = stateAdjustments,
                    FraudPrevention = fraudPrevention,
                    RefundTime = DateTime.UtcNow
                };

                _logger.LogInformation("Refund processed successfully for Player {PlayerId} - Transaction: {TransactionId}",
                    playerId, transactionId);

                return Ok(response);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error processing refund for Transaction {TransactionId}", transactionId);
                return StatusCode(500, new { Message = "Failed to process refund", Code = "REFUND_PROCESSING_ERROR" });
            }
        }

        #endregion

        #region Anti-Pay-to-Win Monitoring

        /// <summary>
        /// Validates victory outcomes against spending influence thresholds
        /// </summary>
        /// <param name="request">Victory validation parameters</param>
        /// <returns>Victory validation result with spending influence analysis</returns>
        [HttpPost("validate-victory-outcomes")]
        [ProducesResponseType(typeof(object), 200)]
        [ProducesResponseType(400)]
        public async Task<IActionResult> ValidateVictoryOutcomes([FromBody] object request)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return BadRequest(new { Message = "Invalid victory validation request", Code = "INVALID_REQUEST" });
                }

                var (playerId, kingdomId) = GetAuthenticatedPlayer();
                var requestDict = System.Text.Json.JsonSerializer.Deserialize<Dictionary<string, object>>(request.ToString() ?? "{}");

                var battleResults = requestDict?.ContainsKey("battleResults") == true ?
                    (Dictionary<string, object>)requestDict["battleResults"] : new();
                var timeframeDays = requestDict?.ContainsKey("timeframeDays") == true ?
                    Convert.ToInt32(requestDict["timeframeDays"]) : 30;

                var validationResult = await _purchaseService.ValidateVictoryOutcomeBalanceAsync(
                    kingdomId, TimeSpan.FromDays(timeframeDays), null);

                var response = new
                {
                    PlayerId = playerId,
                    KingdomId = kingdomId,
                    TimeframeDays = timeframeDays,
                    ValidationResult = validationResult,
                    ValidationTime = DateTime.UtcNow
                };

                _logger.LogInformation("Victory outcomes validated for Player {PlayerId} over {Days} days",
                    playerId, timeframeDays);

                return Ok(response);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error validating victory outcomes for Player {PlayerId}", GetAuthenticatedPlayer().PlayerId);
                return StatusCode(500, new { Message = "Failed to validate victory outcomes", Code = "VICTORY_VALIDATION_ERROR" });
            }
        }

        /// <summary>
        /// Monitors competitive effectiveness ensuring free players maintain viability
        /// </summary>
        /// <param name="timeframeDays">Analysis timeframe (default: 30 days)</param>
        /// <returns>Competitive effectiveness analysis with balance recommendations</returns>
        [HttpGet("monitor-competitive-effectiveness")]
        [ProducesResponseType(typeof(object), 200)]
        public async Task<IActionResult> MonitorCompetitiveEffectiveness([FromQuery] int timeframeDays = 30)
        {
            try
            {
                var (playerId, kingdomId) = GetAuthenticatedPlayer();

                var effectivenessAnalysis = await _purchaseService.CalculateCompetitiveEffectivenessAsync(
                    playerId, kingdomId, new List<int>());

                var response = new
                {
                    PlayerId = playerId,
                    KingdomId = kingdomId,
                    TimeframeDays = timeframeDays,
                    EffectivenessAnalysis = effectivenessAnalysis,
                    MonitoringTime = DateTime.UtcNow
                };

                return Ok(response);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error monitoring competitive effectiveness for Player {PlayerId}", GetAuthenticatedPlayer().PlayerId);
                return StatusCode(500, new { Message = "Failed to monitor competitive effectiveness", Code = "EFFECTIVENESS_MONITORING_ERROR" });
            }
        }

        /// <summary>
        /// Applies dynamic balance adjustments to maintain fair gameplay
        /// </summary>
        /// <param name="request">Balance adjustment parameters</param>
        /// <returns>Balance adjustment result with applied compensations</returns>
        [HttpPost("apply-balance-adjustments")]
        [ProducesResponseType(typeof(object), 200)]
        [ProducesResponseType(400)]
        [ProducesResponseType(403)] // Insufficient authority for adjustments
        public async Task<IActionResult> ApplyBalanceAdjustments([FromBody] object request)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return BadRequest(new { Message = "Invalid balance adjustment request", Code = "INVALID_REQUEST" });
                }

                var (playerId, kingdomId) = GetAuthenticatedPlayer();
                var requestDict = System.Text.Json.JsonSerializer.Deserialize<Dictionary<string, object>>(request.ToString() ?? "{}");

                var imbalanceDetection = requestDict?.ContainsKey("imbalanceDetection") == true ?
                    (Dictionary<string, object>)requestDict["imbalanceDetection"] : new();
                var compensationTypes = requestDict?.ContainsKey("compensationTypes") == true ?
                    ((System.Text.Json.JsonElement)requestDict["compensationTypes"]).Deserialize<List<string>>() ?? new() : new();

                var balanceResult = await _purchaseService.ImplementBalanceAdjustmentsAsync(
                    new List<int> { playerId }, kingdomId, "dynamic", imbalanceDetection);
                var success = balanceResult.ContainsKey("success") && (bool)balanceResult["success"];

                if (!success)
                {
                    return Forbid("Balance adjustments failed - insufficient authority or invalid adjustments");
                }

                var response = new
                {
                    PlayerId = playerId,
                    KingdomId = kingdomId,
                    Success = success,
                    BalanceResult = balanceResult,
                    AdjustmentTime = DateTime.UtcNow
                };

                _logger.LogInformation("Balance adjustments applied for Player {PlayerId} in Kingdom {KingdomId}",
                    playerId, kingdomId);

                return Ok(response);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error applying balance adjustments for Player {PlayerId}", GetAuthenticatedPlayer().PlayerId);
                return StatusCode(500, new { Message = "Failed to apply balance adjustments", Code = "BALANCE_ADJUSTMENT_ERROR" });
            }
        }

        /// <summary>
        /// Monitors spending dominance patterns within kingdom
        /// </summary>
        /// <param name="timeframeDays">Monitoring timeframe (default: 30 days)</param>
        /// <returns>Spending dominance analysis with intervention recommendations</returns>
        [HttpGet("monitor-spending-dominance")]
        [ProducesResponseType(typeof(object), 200)]
        public async Task<IActionResult> MonitorSpendingDominance([FromQuery] int timeframeDays = 30)
        {
            try
            {
                var (playerId, kingdomId) = GetAuthenticatedPlayer();

                var dominanceAnalysis = await _purchaseService.MonitorPayToWinDominanceAsync(
                    playerId, kingdomId, TimeSpan.FromDays(timeframeDays));

                var response = new
                {
                    PlayerId = playerId,
                    KingdomId = kingdomId,
                    TimeframeDays = timeframeDays,
                    DominanceAnalysis = dominanceAnalysis,
                    MonitoringTime = DateTime.UtcNow
                };

                return Ok(response);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error monitoring spending dominance for Player {PlayerId}", GetAuthenticatedPlayer().PlayerId);
                return StatusCode(500, new { Message = "Failed to monitor spending dominance", Code = "DOMINANCE_MONITORING_ERROR" });
            }
        }

        #endregion

        #region VIP System Management

        /// <summary>
        /// Processes VIP progression with secret tier handling and chargeback protection
        /// </summary>
        /// <param name="request">VIP progression parameters</param>
        /// <returns>VIP progression result with tier advancement and benefits</returns>
        [HttpPost("vip/process-progression")]
        [ProducesResponseType(typeof(object), 200)]
        [ProducesResponseType(400)]
        [ProducesResponseType(409)] // VIP progression blocked
        public async Task<IActionResult> ProcessVipProgression([FromBody] object request)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return BadRequest(new { Message = "Invalid VIP progression request", Code = "INVALID_REQUEST" });
                }

                var (playerId, kingdomId) = GetAuthenticatedPlayer();
                var requestDict = System.Text.Json.JsonSerializer.Deserialize<Dictionary<string, object>>(request.ToString() ?? "{}");

                var spendingAmount = requestDict?.ContainsKey("spendingAmount") == true ?
                    Convert.ToDecimal(requestDict["spendingAmount"]) : 0m;
                var tierProgression = requestDict?.ContainsKey("tierProgression") == true ?
                    (Dictionary<string, object>)requestDict["tierProgression"] : new();

                var (tierAdvanced, newVipTier, isSecretTier, newBenefits, chargebackRisk, skillAlternatives) =
                    await _purchaseService.ManageVipProgressionAsync(
                        playerId, kingdomId, spendingAmount, "purchase");

                if (!tierAdvanced)
                {
                    return Conflict(new { Message = "VIP progression blocked - spending validation failed or chargeback risk detected", Code = "VIP_PROGRESSION_BLOCKED" });
                }

                var response = new
                {
                    PlayerId = playerId,
                    TierAdvanced = tierAdvanced,
                    NewVipTier = newVipTier,
                    IsSecretTier = isSecretTier,
                    NewBenefits = newBenefits,
                    ChargebackRisk = chargebackRisk,
                    SkillAlternatives = skillAlternatives,
                    ProgressionTime = DateTime.UtcNow
                };

                _logger.LogInformation("VIP progression processed for Player {PlayerId} - New Tier: {Tier}, Secret: {Secret}",
                    playerId, newVipTier, isSecretTier);

                return Ok(response);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error processing VIP progression for Player {PlayerId}", GetAuthenticatedPlayer().PlayerId);
                return StatusCode(500, new { Message = "Failed to process VIP progression", Code = "VIP_PROGRESSION_ERROR" });
            }
        }

        /// <summary>
        /// Claims VIP benefits with convenience focus and skill alternatives
        /// </summary>
        /// <param name="request">VIP benefit claim parameters</param>
        /// <returns>VIP benefit claim result with applied benefits</returns>
        [HttpPost("vip/claim-benefits")]
        [ProducesResponseType(typeof(object), 200)]
        [ProducesResponseType(400)]
        [ProducesResponseType(403)] // Benefits not available or already claimed
        public async Task<IActionResult> ClaimVipBenefits([FromBody] object request)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return BadRequest(new { Message = "Invalid VIP benefit claim request", Code = "INVALID_REQUEST" });
                }

                var (playerId, kingdomId) = GetAuthenticatedPlayer();
                var requestDict = System.Text.Json.JsonSerializer.Deserialize<Dictionary<string, object>>(request.ToString() ?? "{}");

                var benefitType = requestDict?.ContainsKey("benefitType") == true ?
                    requestDict["benefitType"].ToString() : "";
                var claimParameters = requestDict?.ContainsKey("claimParameters") == true ?
                    (Dictionary<string, object>)requestDict["claimParameters"] : new();

                var (success, appliedBenefits, validationWarnings) =
                    await _purchaseService.ProcessVipBenefitClaimAsync(
                        playerId, kingdomId, benefitType, claimParameters);

                if (!success)
                {
                    return Forbid("VIP benefit claim failed - benefits not available, already claimed, or invalid tier");
                }

                var response = new
                {
                    PlayerId = playerId,
                    BenefitType = benefitType,
                    Success = success,
                    AppliedBenefits = appliedBenefits,
                    ValidationWarnings = validationWarnings,
                    ClaimTime = DateTime.UtcNow
                };

                _logger.LogInformation("VIP benefits claimed for Player {PlayerId} - Benefit Type: {Type}",
                    playerId, benefitType);

                return Ok(response);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error claiming VIP benefits for Player {PlayerId}", GetAuthenticatedPlayer().PlayerId);
                return StatusCode(500, new { Message = "Failed to claim VIP benefits", Code = "VIP_BENEFIT_CLAIM_ERROR" });
            }
        }

        /// <summary>
        /// Validates VIP tier against chargeback protection systems
        /// </summary>
        /// <param name="vipTier">VIP tier to validate</param>
        /// <returns>VIP tier validation result with chargeback risk assessment</returns>
        [HttpGet("vip/{vipTier}/validate-protection")]
        [ProducesResponseType(typeof(object), 200)]
        [ProducesResponseType(400)]
        public async Task<IActionResult> ValidateVipTierProtection(int vipTier)
        {
            try
            {
                var (playerId, kingdomId) = GetAuthenticatedPlayer();

                var chargebackDetails = new Dictionary<string, object> { ["vipTier"] = vipTier };
                var protectionResult = await _purchaseService.HandleVipChargebackProtectionAsync(
                    playerId, kingdomId, chargebackDetails);

                var response = new
                {
                    PlayerId = playerId,
                    VipTier = vipTier,
                    ProtectionResult = protectionResult,
                    ValidationTime = DateTime.UtcNow
                };

                return Ok(response);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error validating VIP tier protection for Player {PlayerId}, Tier: {Tier}",
                    GetAuthenticatedPlayer().PlayerId, vipTier);
                return StatusCode(500, new { Message = "Failed to validate VIP tier protection", Code = "VIP_VALIDATION_ERROR" });
            }
        }

        #endregion

        #region Skill-Based Alternatives

        /// <summary>
        /// Provides skill-based alternatives to premium features
        /// </summary>
        /// <param name="request">Skill alternative parameters</param>
        /// <returns>Skill-based alternative options with achievement paths</returns>
        [HttpPost("skill-alternatives/provide")]
        [ProducesResponseType(typeof(object), 200)]
        [ProducesResponseType(400)]
        public async Task<IActionResult> ProvideSkillAlternatives([FromBody] object request)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return BadRequest(new { Message = "Invalid skill alternatives request", Code = "INVALID_REQUEST" });
                }

                var (playerId, kingdomId) = GetAuthenticatedPlayer();
                var requestDict = System.Text.Json.JsonSerializer.Deserialize<Dictionary<string, object>>(request.ToString() ?? "{}");

                var premiumFeature = requestDict?.ContainsKey("premiumFeature") == true ?
                    requestDict["premiumFeature"].ToString() : "";
                var playerSkillLevel = requestDict?.ContainsKey("playerSkillLevel") == true ?
                    Convert.ToInt32(requestDict["playerSkillLevel"]) : 1;

                var skillAlternatives = await _purchaseService.ProvideSkillBasedAlternativesAsync(
                    playerId, kingdomId, premiumFeature);

                var response = new
                {
                    PlayerId = playerId,
                    PremiumFeature = premiumFeature,
                    PlayerSkillLevel = playerSkillLevel,
                    SkillAlternatives = skillAlternatives,
                    ProvidedTime = DateTime.UtcNow
                };

                _logger.LogInformation("Skill alternatives provided for Player {PlayerId} - Feature: {Feature}",
                    playerId, premiumFeature);

                return Ok(response);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error providing skill alternatives for Player {PlayerId}", GetAuthenticatedPlayer().PlayerId);
                return StatusCode(500, new { Message = "Failed to provide skill alternatives", Code = "SKILL_ALTERNATIVES_ERROR" });
            }
        }

        /// <summary>
        /// Validates alternative effectiveness ensuring competitive viability
        /// </summary>
        /// <param name="request">Alternative effectiveness parameters</param>
        /// <returns>Alternative effectiveness validation with competitive analysis</returns>
        [HttpPost("skill-alternatives/validate-effectiveness")]
        [ProducesResponseType(typeof(object), 200)]
        [ProducesResponseType(400)]
        public async Task<IActionResult> ValidateAlternativeEffectiveness([FromBody] object request)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return BadRequest(new { Message = "Invalid effectiveness validation request", Code = "INVALID_REQUEST" });
                }

                var (playerId, kingdomId) = GetAuthenticatedPlayer();
                var requestDict = System.Text.Json.JsonSerializer.Deserialize<Dictionary<string, object>>(request.ToString() ?? "{}");

                var alternativeUsage = requestDict?.ContainsKey("alternativeUsage") == true ?
                    (Dictionary<string, object>)requestDict["alternativeUsage"] : new();
                var competitiveContext = requestDict?.ContainsKey("competitiveContext") == true ?
                    (Dictionary<string, object>)requestDict["competitiveContext"] : new();

                var effectivenessResult = await _purchaseService.ValidateSkillBasedAlternativeEffectivenessAsync(
                    kingdomId, "comprehensive", competitiveContext);

                var response = new
                {
                    PlayerId = playerId,
                    EffectivenessResult = effectivenessResult,
                    ValidationTime = DateTime.UtcNow
                };

                return Ok(response);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error validating alternative effectiveness for Player {PlayerId}", GetAuthenticatedPlayer().PlayerId);
                return StatusCode(500, new { Message = "Failed to validate alternative effectiveness", Code = "EFFECTIVENESS_VALIDATION_ERROR" });
            }
        }

        /// <summary>
        /// Processes achievement-based rewards as alternatives to purchases
        /// </summary>
        /// <param name="request">Achievement reward parameters</param>
        /// <returns>Achievement reward result with granted benefits</returns>
        [HttpPost("skill-alternatives/process-achievement-rewards")]
        [ProducesResponseType(typeof(object), 200)]
        [ProducesResponseType(400)]
        [ProducesResponseType(403)] // Achievement not qualified or already claimed
        public async Task<IActionResult> ProcessAchievementRewards([FromBody] object request)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return BadRequest(new { Message = "Invalid achievement reward request", Code = "INVALID_REQUEST" });
                }

                var (playerId, kingdomId) = GetAuthenticatedPlayer();
                var requestDict = System.Text.Json.JsonSerializer.Deserialize<Dictionary<string, object>>(request.ToString() ?? "{}");

                var achievementType = requestDict?.ContainsKey("achievementType") == true ?
                    requestDict["achievementType"].ToString() : "";
                var achievementCriteria = requestDict?.ContainsKey("achievementCriteria") == true ?
                    (Dictionary<string, object>)requestDict["achievementCriteria"] : new();

                var rewardResult = await _purchaseService.CalculateAchievementBasedRewardsAsync(
                    playerId, kingdomId, achievementType, 30);
                var success = rewardResult.ContainsKey("success") && (bool)rewardResult["success"];

                if (!success)
                {
                    return Forbid("Achievement reward failed - criteria not met, already claimed, or invalid achievement");
                }

                var response = new
                {
                    PlayerId = playerId,
                    AchievementType = achievementType,
                    Success = success,
                    RewardResult = rewardResult,
                    ProcessingTime = DateTime.UtcNow
                };

                _logger.LogInformation("Achievement rewards processed for Player {PlayerId} - Achievement: {Type}",
                    playerId, achievementType);

                return Ok(response);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error processing achievement rewards for Player {PlayerId}", GetAuthenticatedPlayer().PlayerId);
                return StatusCode(500, new { Message = "Failed to process achievement rewards", Code = "ACHIEVEMENT_REWARD_ERROR" });
            }
        }

        #endregion

        #region Player Protection Systems

        /// <summary>
        /// Monitors player spending patterns for health and protection needs
        /// </summary>
        /// <param name="timeframeDays">Monitoring timeframe (default: 30 days)</param>
        /// <returns>Spending pattern analysis with health recommendations</returns>
        [HttpGet("protection/monitor-spending-patterns")]
        [ProducesResponseType(typeof(object), 200)]
        public async Task<IActionResult> MonitorSpendingPatterns([FromQuery] int timeframeDays = 30)
        {
            try
            {
                var (playerId, kingdomId) = GetAuthenticatedPlayer();

                var spendingAnalysis = await _purchaseService.GenerateSpendingAnalyticsAsync(
                    playerId, kingdomId, "comprehensive", timeframeDays);

                var response = new
                {
                    PlayerId = playerId,
                    TimeframeDays = timeframeDays,
                    SpendingAnalysis = spendingAnalysis,
                    MonitoringTime = DateTime.UtcNow
                };

                return Ok(response);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error monitoring spending patterns for Player {PlayerId}", GetAuthenticatedPlayer().PlayerId);
                return StatusCode(500, new { Message = "Failed to monitor spending patterns", Code = "SPENDING_MONITORING_ERROR" });
            }
        }

        /// <summary>
        /// Implements spending limits with player protection measures
        /// </summary>
        /// <param name="request">Spending limit parameters</param>
        /// <returns>Spending limit implementation result</returns>
        [HttpPost("protection/implement-spending-limits")]
        [ProducesResponseType(typeof(object), 200)]
        [ProducesResponseType(400)]
        public async Task<IActionResult> ImplementSpendingLimits([FromBody] object request)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return BadRequest(new { Message = "Invalid spending limits request", Code = "INVALID_REQUEST" });
                }

                var (playerId, kingdomId) = GetAuthenticatedPlayer();
                var requestDict = System.Text.Json.JsonSerializer.Deserialize<Dictionary<string, object>>(request.ToString() ?? "{}");

                var limitType = requestDict?.ContainsKey("limitType") == true ?
                    requestDict["limitType"].ToString() : "daily";
                var limitAmount = requestDict?.ContainsKey("limitAmount") == true ?
                    Convert.ToDecimal(requestDict["limitAmount"]) : 50m;
                var protectionReason = requestDict?.ContainsKey("protectionReason") == true ?
                    requestDict["protectionReason"].ToString() : "player_welfare";

                var spendingData = new Dictionary<string, object> { ["currentSpending"] = 0 };
                var limitParameters = new Dictionary<string, object>
                {
                    ["limitType"] = limitType,
                    ["limitAmount"] = limitAmount,
                    ["reason"] = protectionReason
                };

                var (limitsApplied, spendingLimits, healthGuidance) =
                    await _purchaseService.ManageHealthySpendingLimitsAsync(
                        playerId, kingdomId, spendingData, limitParameters);

                var response = new
                {
                    PlayerId = playerId,
                    LimitsApplied = limitsApplied,
                    LimitType = limitType,
                    LimitAmount = limitAmount,
                    ProtectionReason = protectionReason,
                    SpendingLimits = spendingLimits,
                    HealthGuidance = healthGuidance,
                    ImplementationTime = DateTime.UtcNow
                };

                _logger.LogInformation("Spending limits implemented for Player {PlayerId} - Type: {Type}, Amount: {Amount}",
                    playerId, limitType, limitAmount);

                return Ok(response);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error implementing spending limits for Player {PlayerId}", GetAuthenticatedPlayer().PlayerId);
                return StatusCode(500, new { Message = "Failed to implement spending limits", Code = "SPENDING_LIMITS_ERROR" });
            }
        }

        /// <summary>
        /// Assesses player protection needs based on spending behavior
        /// </summary>
        /// <param name="request">Protection assessment parameters</param>
        /// <returns>Protection needs assessment with intervention recommendations</returns>
        [HttpPost("protection/assess-needs")]
        [ProducesResponseType(typeof(object), 200)]
        [ProducesResponseType(400)]
        public async Task<IActionResult> AssessPlayerProtectionNeeds([FromBody] object request)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return BadRequest(new { Message = "Invalid protection assessment request", Code = "INVALID_REQUEST" });
                }

                var (playerId, kingdomId) = GetAuthenticatedPlayer();
                var requestDict = System.Text.Json.JsonSerializer.Deserialize<Dictionary<string, object>>(request.ToString() ?? "{}");

                var spendingPattern = requestDict?.ContainsKey("spendingPattern") == true ?
                    (Dictionary<string, object>)requestDict["spendingPattern"] : new();

                var protectionAssessment = await _purchaseService.AssessPlayerProtectionNeedsAsync(
                    playerId, kingdomId, spendingPattern);

                var response = new
                {
                    PlayerId = playerId,
                    ProtectionAssessment = protectionAssessment,
                    AssessmentTime = DateTime.UtcNow
                };

                return Ok(response);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error assessing player protection needs for Player {PlayerId}", GetAuthenticatedPlayer().PlayerId);
                return StatusCode(500, new { Message = "Failed to assess player protection needs", Code = "PROTECTION_ASSESSMENT_ERROR" });
            }
        }

        #endregion

        #region Revenue Analytics

        /// <summary>
        /// Generates ethical revenue analytics balancing business goals with player welfare
        /// </summary>
        /// <param name="request">Revenue analytics parameters</param>
        /// <returns>Ethical revenue analytics with sustainability insights</returns>
        [HttpPost("analytics/ethical-revenue")]
        [ProducesResponseType(typeof(object), 200)]
        [ProducesResponseType(400)]
        [ProducesResponseType(403)] // Insufficient authority for revenue analytics
        public async Task<IActionResult> GenerateEthicalRevenueAnalytics([FromBody] object request)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return BadRequest(new { Message = "Invalid revenue analytics request", Code = "INVALID_REQUEST" });
                }

                var (playerId, kingdomId) = GetAuthenticatedPlayer();
                var requestDict = System.Text.Json.JsonSerializer.Deserialize<Dictionary<string, object>>(request.ToString() ?? "{}");

                var kingdomIds = requestDict?.ContainsKey("kingdomIds") == true ?
                    ((System.Text.Json.JsonElement)requestDict["kingdomIds"]).Deserialize<List<int>>() ?? new() { kingdomId } :
                    new() { kingdomId };
                var analysisType = requestDict?.ContainsKey("analysisType") == true ?
                    requestDict["analysisType"].ToString() : "comprehensive";
                var timeframeDays = requestDict?.ContainsKey("timeframeDays") == true ?
                    Convert.ToInt32(requestDict["timeframeDays"]) : 30;

                var revenueAnalytics = await _purchaseService.GenerateEthicalRevenueAnalyticsAsync(
                    kingdomIds, analysisType, timeframeDays);

                var response = new
                {
                    PlayerId = playerId,
                    KingdomIds = kingdomIds,
                    AnalysisType = analysisType,
                    TimeframeDays = timeframeDays,
                    RevenueAnalytics = revenueAnalytics,
                    GenerationTime = DateTime.UtcNow
                };

                _logger.LogInformation("Ethical revenue analytics generated for Kingdoms: {KingdomIds}, Type: {Type}",
                    string.Join(",", kingdomIds), analysisType);

                return Ok(response);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error generating ethical revenue analytics for Player {PlayerId}", GetAuthenticatedPlayer().PlayerId);
                return StatusCode(500, new { Message = "Failed to generate revenue analytics", Code = "REVENUE_ANALYTICS_ERROR" });
            }
        }

        /// <summary>
        /// Analyzes purchase conversion patterns with player satisfaction correlation
        /// </summary>
        /// <param name="conversionType">Type of conversion to analyze (default: comprehensive)</param>
        /// <returns>Conversion pattern analysis with satisfaction correlation</returns>
        [HttpGet("analytics/conversion-patterns")]
        [ProducesResponseType(typeof(object), 200)]
        public async Task<IActionResult> AnalyzePurchaseConversionPatterns([FromQuery] string conversionType = "comprehensive")
        {
            try
            {
                var (playerId, kingdomId) = GetAuthenticatedPlayer();

                var conversionAnalysis = await _purchaseService.AnalyzePurchaseConversionPatternsAsync(
                    kingdomId, conversionType);

                var response = new
                {
                    PlayerId = playerId,
                    KingdomId = kingdomId,
                    ConversionType = conversionType,
                    ConversionAnalysis = conversionAnalysis,
                    AnalysisTime = DateTime.UtcNow
                };

                return Ok(response);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error analyzing conversion patterns for Kingdom {KingdomId}", GetAuthenticatedPlayer().KingdomId);
                return StatusCode(500, new { Message = "Failed to analyze conversion patterns", Code = "CONVERSION_ANALYSIS_ERROR" });
            }
        }

        /// <summary>
        /// Calculates sustainable monetization metrics prioritizing long-term value
        /// </summary>
        /// <param name="request">Sustainability metrics parameters</param>
        /// <returns>Sustainable monetization metrics with viability assessment</returns>
        [HttpPost("analytics/sustainable-monetization")]
        [ProducesResponseType(typeof(object), 200)]
        [ProducesResponseType(400)]
        [ProducesResponseType(403)]
        public async Task<IActionResult> CalculateSustainableMonetizationMetrics([FromBody] object request)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return BadRequest(new { Message = "Invalid sustainability metrics request", Code = "INVALID_REQUEST" });
                }

                var (playerId, kingdomId) = GetAuthenticatedPlayer();
                var requestDict = System.Text.Json.JsonSerializer.Deserialize<Dictionary<string, object>>(request.ToString() ?? "{}");

                var kingdomIds = requestDict?.ContainsKey("kingdomIds") == true ?
                    ((System.Text.Json.JsonElement)requestDict["kingdomIds"]).Deserialize<List<int>>() ?? new() { kingdomId } :
                    new() { kingdomId };
                var sustainabilityFactors = requestDict?.ContainsKey("sustainabilityFactors") == true ?
                    (Dictionary<string, object>)requestDict["sustainabilityFactors"] : new();

                var sustainabilityMetrics = await _purchaseService.CalculateSustainableMonetizationMetricsAsync(
                    kingdomIds, sustainabilityFactors);

                var response = new
                {
                    PlayerId = playerId,
                    KingdomIds = kingdomIds,
                    SustainabilityMetrics = sustainabilityMetrics,
                    CalculationTime = DateTime.UtcNow
                };

                _logger.LogInformation("Sustainable monetization metrics calculated for Kingdoms: {KingdomIds}",
                    string.Join(",", kingdomIds));

                return Ok(response);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error calculating sustainable monetization metrics for Player {PlayerId}", GetAuthenticatedPlayer().PlayerId);
                return StatusCode(500, new { Message = "Failed to calculate sustainability metrics", Code = "SUSTAINABILITY_METRICS_ERROR" });
            }
        }

        #endregion

        #region Helper Methods

        /// <summary>
        /// Extracts authenticated player information from JWT claims
        /// </summary>
        /// <returns>Player ID and Kingdom ID from authentication context</returns>
        /// <exception cref="UnauthorizedAccessException">Thrown when authentication claims are invalid</exception>
        private (int PlayerId, int KingdomId) GetAuthenticatedPlayer()
        {
            var playerIdClaim = User.FindFirst("player_id")?.Value;
            var kingdomIdClaim = User.FindFirst("kingdom_id")?.Value;

            if (string.IsNullOrEmpty(playerIdClaim) || string.IsNullOrEmpty(kingdomIdClaim))
            {
                throw new UnauthorizedAccessException("Invalid authentication claims - player or kingdom not found");
            }

            if (!int.TryParse(playerIdClaim, out int playerId) ||
                !int.TryParse(kingdomIdClaim, out int kingdomId))
            {
                throw new UnauthorizedAccessException("Invalid authentication claims - unable to parse player or kingdom ID");
            }

            return (playerId, kingdomId);
        }

        #endregion
    }
}