/*
 * File: ShadowedRealms.Core/Models/Purchase/PurchaseLog.cs
 * Created: 2025-10-19
 * Last Modified: 2025-10-20
 * Description: Purchase tracking system for all monetization activities including IAP, gold spending, VIP subscriptions, and dragon purchases. Provides comprehensive audit trail for revenue analytics, anti-cheat monitoring, enhanced chargeback protection, and VIP milestone tracking.
 * Last Edit Notes: Updated to implement IKingdomScoped and fixed property names to match repository expectations
 */

using ShadowedRealms.Core.Interfaces;
using ShadowedRealms.Core.Models.Kingdom;
using ShadowedRealms.Core.Models.Player;
using ShadowedRealms.Core.Models.Alliance;
using System.ComponentModel.DataAnnotations;
using System.Text.Json;

namespace ShadowedRealms.Core.Models.Purchase
{
    public class PurchaseLog : IKingdomScoped
    {
        public int Id { get; set; }

        [Required]
        public int PlayerId { get; set; }

        [Required]
        public int KingdomId { get; set; }

        public int? AllianceId { get; set; }

        [Required]
        [StringLength(100)]
        public string ProductId { get; set; } = string.Empty;

        [Required]
        [StringLength(200)]
        public string ProductName { get; set; } = string.Empty;

        [Required]
        public PurchaseType PurchaseType { get; set; }

        [Required]
        public PaymentMethod PaymentMethod { get; set; }

        [Required]
        [Range(0, double.MaxValue)]
        public decimal Amount { get; set; }

        [Required]
        [StringLength(10)]
        public string Currency { get; set; } = "USD";

        // Repository expects these specific property names
        [Required]
        public DateTime PurchaseDate { get; set; } = DateTime.UtcNow;

        public DateTime? ProcessedAt { get; set; }

        [Required]
        public PurchaseStatus Status { get; set; } = PurchaseStatus.Pending;

        // Enhanced Platform-specific transaction tracking for chargeback protection
        [Required]
        [StringLength(200)]
        public string TransactionId { get; set; } = string.Empty; // Repository expects TransactionId

        [StringLength(200)]
        public string PlatformTransactionId { get; set; } = string.Empty;

        [StringLength(500)]
        public string? PlatformReceiptData { get; set; }

        [Required]
        [StringLength(20)]
        public string Platform { get; set; } = string.Empty; // iOS, Android, PC

        [StringLength(100)]
        public string? PlatformUserId { get; set; }

        [StringLength(50)]
        public string? DeviceInfo { get; set; } // Repository expects DeviceInfo

        [StringLength(100)]
        public string? IPAddress { get; set; } // Repository expects IPAddress (not IpAddress)

        [StringLength(200)]
        public string? UserAgent { get; set; }

        // Enhanced Gold Economy Tracking
        [Range(0, int.MaxValue)]
        public int GoldPurchased { get; set; } = 0;

        [Range(0, int.MaxValue)]
        public int GoldSpent { get; set; } = 0;

        [Range(0, int.MaxValue)]
        public int GoldBalanceBefore { get; set; } = 0;

        [Range(0, int.MaxValue)]
        public int GoldBalanceAfter { get; set; } = 0;

        // Enhanced Financial Tracking
        [Range(0, double.MaxValue)]
        public decimal PlatformFee { get; set; } = 0m;

        [Range(0, double.MaxValue)]
        public decimal NetRevenue { get; set; } = 0m;

        [Range(0, double.MaxValue)]
        public decimal TaxAmount { get; set; } = 0m;

        [Range(0, double.MaxValue)]
        public decimal RefundAmount { get; set; } = 0m;

        // Chargeback Protection and Risk Management (Repository expects these specific property names)
        public bool IsChargedBack { get; set; } = false;

        public DateTime? ChargebackDate { get; set; }

        [StringLength(500)]
        public string? ChargebackReason { get; set; }

        public decimal? ChargebackPenalty { get; set; }

        public bool IsSuspicious { get; set; } = false;

        [StringLength(1000)]
        public string? FraudReason { get; set; }

        public bool IsRefunded { get; set; } = false;

        public DateTime? RefundDate { get; set; }

        [StringLength(500)]
        public string? RefundReason { get; set; }

        public bool IsConfirmed { get; set; } = false;

        [StringLength(1000)]
        public string? Notes { get; set; }

        // VIP System Integration
        public bool IsVipPurchase { get; set; } = false;

        [Range(0, 15)]
        public int VipLevelBefore { get; set; } = 0;

        [Range(0, 15)]
        public int VipLevelAfter { get; set; } = 0;

        [Range(0, 365)]
        public int VipDaysAdded { get; set; } = 0;

        // VIP Milestone and Rewards Tracking (KoA-inspired system)
        [Range(0, int.MaxValue)]
        public int VipPointsEarned { get; set; } = 0; // Points earned from this purchase

        [Range(0, int.MaxValue)]
        public int VipPointsBefore { get; set; } = 0;

        [Range(0, int.MaxValue)]
        public int VipPointsAfter { get; set; } = 0;

        public bool TriggeredVipMilestone { get; set; } = false;

        [StringLength(100)]
        public string? VipMilestoneReached { get; set; }

        public bool IsEligibleForMonthlyReward { get; set; } = false;

        public bool IsEligibleForYearlyReward { get; set; } = false;

        // Secret tier tracking (undisclosed thresholds like KoA)
        [Range(0, 15)]
        public int SecretSpendingTierBefore { get; set; } = 0;

        [Range(0, 15)]
        public int SecretSpendingTierAfter { get; set; } = 0;

        public bool UnlockedNewSecretTier { get; set; } = false;

        // Dragon System Integration
        public bool IsDragonPurchase { get; set; } = false;

        [StringLength(50)]
        public string? DragonType { get; set; }

        [Range(0, 30)]
        public int DragonDaysAdded { get; set; } = 0;

        [StringLength(200)]
        public string? DragonSkillsUnlocked { get; set; }

        // Speed Boost Tracking
        public bool IsSpeedBoostPurchase { get; set; } = false;

        [Range(0, 1000)]
        public int SpeedBoostQuantity { get; set; } = 0;

        [Range(1, 10)]
        public int SpeedBoostLevel { get; set; } = 0;

        [Range(0, 168)] // Up to 1 week
        public int SpeedBoostHours { get; set; } = 0;

        // Stealth System Integration
        public bool IsStealthPurchase { get; set; } = false;

        [Range(0, 100)]
        public int StealthUsesAdded { get; set; } = 0;

        [StringLength(50)]
        public string? StealthType { get; set; } // "Premium", "Instant", "Advanced"

        // Resource Package Tracking
        public bool IsResourcePackage { get; set; } = false;

        [Range(0, long.MaxValue)]
        public long FoodReceived { get; set; } = 0;

        [Range(0, long.MaxValue)]
        public long WoodReceived { get; set; } = 0;

        [Range(0, long.MaxValue)]
        public long IronReceived { get; set; } = 0;

        [Range(0, long.MaxValue)]
        public long SilverReceived { get; set; } = 0;

        [Range(0, long.MaxValue)]
        public long MithrilReceived { get; set; } = 0;

        // Construction and Training Boosts
        public bool IsConstructionBoost { get; set; } = false;

        public bool IsTrainingBoost { get; set; } = false;

        public bool IsResearchBoost { get; set; } = false;

        [Range(0, 168)]
        public int BoostHours { get; set; } = 0;

        [Range(0, 500)]
        public int BoostPercentage { get; set; } = 0;

        // Anti-Pay-to-Win Tracking
        [Range(0, 100)]
        public double SkillAlternativeUsed { get; set; } = 0; // Percentage of skill-based alternative used

        public bool HasSkillBasedAlternative { get; set; } = false;

        [StringLength(200)]
        public string? SkillAlternativeDescription { get; set; }

        [Range(0, double.MaxValue)]
        public decimal TimeInvestmentHours { get; set; } = 0; // Time player could have invested instead

        // Bundle and Package Information
        public bool IsBundle { get; set; } = false;

        [StringLength(1000)]
        public string? BundleContents { get; set; }

        [Range(0, 100)]
        public double BundleDiscountPercentage { get; set; } = 0;

        // Enhanced Refund and Chargeback Tracking (keeping legacy properties for compatibility)
        public bool WasRefunded { get; set; } = false;

        public DateTime? RefundedAt { get; set; }

        public bool WasChargeback { get; set; } = false;

        public DateTime? ChargebackAt { get; set; }

        public DateTime? ChargebackDisputeDeadline { get; set; }

        public bool ChargebackDisputed { get; set; } = false;

        public ChargebackDisputeStatus? DisputeStatus { get; set; }

        [Range(0, double.MaxValue)]
        public decimal ChargebackFee { get; set; } = 0;

        // Enhanced Fraud Detection and Chargeback Prevention
        [Range(0, 100)]
        public int FraudScore { get; set; } = 0;

        public bool IsFraudSuspected { get; set; } = false;

        [StringLength(500)]
        public string? FraudNotes { get; set; }

        public bool RequiresManualReview { get; set; } = false;

        public bool IsHighRiskTransaction { get; set; } = false;

        [Range(0, int.MaxValue)]
        public int MinutesFromRegistration { get; set; } = 0; // Time since account creation

        [Range(0, int.MaxValue)]
        public int PurchasesInLast24Hours { get; set; } = 0;

        [Range(0, double.MaxValue)]
        public decimal SpendingInLast24Hours { get; set; } = 0;

        public bool IsVelocityFlagged { get; set; } = false; // Too many purchases too quickly

        public bool IsNewDevicePurchase { get; set; } = false; // First purchase from this device

        // Enhanced Customer Segmentation - Monthly AND Lifetime
        [Range(0, double.MaxValue)]
        public decimal MonthlySpendingBefore { get; set; } = 0;

        [Range(0, double.MaxValue)]
        public decimal MonthlySpendingAfter { get; set; } = 0;

        [Range(0, double.MaxValue)]
        public decimal LifetimeSpendingBefore { get; set; } = 0;

        [Range(0, double.MaxValue)]
        public decimal LifetimeSpendingAfter { get; set; } = 0;

        [Range(0, int.MaxValue)]
        public int MonthlyPurchaseCount { get; set; } = 0;

        [Range(0, int.MaxValue)]
        public int LifetimePurchaseCount { get; set; } = 0;

        // Detailed Purchase Data (JSON storage)
        [StringLength(2000)]
        public string? DetailedPurchaseData { get; set; }

        [StringLength(1000)]
        public string? PurchaseNotes { get; set; }

        // Analytics and Conversion Tracking
        [StringLength(100)]
        public string? CampaignId { get; set; }

        [StringLength(100)]
        public string? PromotionCode { get; set; }

        public bool IsFirstPurchase { get; set; } = false;

        public bool IsFirstMonthlyPurchase { get; set; } = false;

        [Range(0, int.MaxValue)]
        public int DaysSinceLastPurchase { get; set; } = 0;

        // Navigation Properties
        public virtual Player.Player Player { get; set; } = null!;

        public virtual Kingdom.Kingdom Kingdom { get; set; } = null!;

        public virtual Alliance.Alliance? Alliance { get; set; }

        // Computed Properties - Enhanced Customer Segmentation
        public long TotalResourcesReceived => FoodReceived + WoodReceived + IronReceived + SilverReceived + MithrilReceived;

        public bool IsSuccessfulPurchase => Status == PurchaseStatus.Completed;

        public bool IsPendingOrFailed => Status == PurchaseStatus.Pending || Status == PurchaseStatus.Failed;

        public decimal NetAmount => Amount - RefundAmount - ChargebackFee;

        public bool IsHighValuePurchase => Amount >= 50m; // $50+ purchases

        public bool IsRecentPurchase => (DateTime.UtcNow - PurchaseDate).TotalHours <= 24;

        public PurchaseCategory Category => GetPurchaseCategory();

        public decimal DollarPerHour => TimeInvestmentHours > 0 ? Amount / TimeInvestmentHours : 0;

        public bool PromotesSkillBasedPlay => HasSkillBasedAlternative && SkillAlternativeUsed > 50;

        public TimeSpan ProcessingTime => ProcessedAt.HasValue ? ProcessedAt.Value - PurchaseDate : TimeSpan.Zero;

        // Enhanced Customer Segmentation Properties
        public MonthlyCustomerSegment MonthlySegment => GetMonthlyCustomerSegment();

        public LifetimeCustomerSegment LifetimeSegment => GetLifetimeCustomerSegment();

        public bool IsMonthlyWhale => MonthlySpendingAfter >= 500m;

        public bool IsLifetimeWhale => LifetimeSpendingAfter >= 2000m;

        public bool IsChargebackRisk => GetChargebackRisk() >= ChargebackRiskLevel.High;

        public decimal TotalFinancialImpact => NetAmount < 0 ? Math.Abs(NetAmount) + ChargebackFee : NetAmount;

        public bool UnlockedSecretTier => UnlockedNewSecretTier;

        public string SecretTierProgression => $"{SecretSpendingTierBefore}→{SecretSpendingTierAfter}";

        // Business Logic Methods
        public PurchaseCategory GetPurchaseCategory()
        {
            if (IsVipPurchase) return PurchaseCategory.Subscription;
            if (IsDragonPurchase) return PurchaseCategory.Premium;
            if (IsResourcePackage) return PurchaseCategory.Resources;
            if (IsSpeedBoostPurchase || IsConstructionBoost || IsTrainingBoost || IsResearchBoost) return PurchaseCategory.TimeSkip;
            if (IsStealthPurchase) return PurchaseCategory.Convenience;
            if (GoldPurchased > 0) return PurchaseCategory.Currency;

            return PurchaseCategory.Other;
        }

        // Enhanced Customer Segmentation
        public MonthlyCustomerSegment GetMonthlyCustomerSegment()
        {
            return MonthlySpendingAfter switch
            {
                >= 500m => MonthlyCustomerSegment.MonthlyWhale,     // $500+ this month
                >= 200m => MonthlyCustomerSegment.MonthlyDolphin,   // $200-499 this month
                >= 50m => MonthlyCustomerSegment.MonthlyMinnow,     // $50-199 this month
                >= 10m => MonthlyCustomerSegment.MonthlySpender,    // $10-49 this month
                > 0m => MonthlyCustomerSegment.MonthlyOccasional,   // $1-9 this month
                _ => MonthlyCustomerSegment.MonthlyFree              // $0 this month
            };
        }

        public LifetimeCustomerSegment GetLifetimeCustomerSegment()
        {
            return LifetimeSpendingAfter switch
            {
                >= 2000m => LifetimeCustomerSegment.LifetimeMegaWhale, // $2000+ lifetime
                >= 1000m => LifetimeCustomerSegment.LifetimeWhale,     // $1000-1999 lifetime
                >= 500m => LifetimeCustomerSegment.LifetimeDolphin,    // $500-999 lifetime
                >= 100m => LifetimeCustomerSegment.LifetimeMinnow,     // $100-499 lifetime
                >= 20m => LifetimeCustomerSegment.LifetimeSpender,     // $20-99 lifetime
                > 0m => LifetimeCustomerSegment.LifetimeOccasional,    // $1-19 lifetime
                _ => LifetimeCustomerSegment.LifetimeFree              // $0 lifetime
            };
        }

        // Enhanced Chargeback Risk Assessment
        public ChargebackRiskLevel GetChargebackRisk()
        {
            var riskScore = 0;

            // High-risk indicators
            if (MinutesFromRegistration < 60) riskScore += 30; // Purchase within 1 hour of registration
            if (PurchasesInLast24Hours >= 5) riskScore += 25; // 5+ purchases in 24 hours
            if (SpendingInLast24Hours >= 200m) riskScore += 20; // $200+ in 24 hours
            if (IsNewDevicePurchase && Amount >= 100m) riskScore += 15; // Large purchase from new device
            if (IsHighValuePurchase && IsFirstPurchase) riskScore += 15; // First purchase is high value
            if (string.IsNullOrWhiteSpace(IPAddress)) riskScore += 10; // No IP tracking

            // Medium-risk indicators
            if (MinutesFromRegistration < 1440) riskScore += 10; // Purchase within 24 hours of registration
            if (PurchasesInLast24Hours >= 3) riskScore += 10; // 3+ purchases in 24 hours
            if (Amount >= 50m && MonthlyPurchaseCount == 1) riskScore += 8; // High-value first monthly purchase
            if (PaymentMethod == PaymentMethod.CreditCard) riskScore += 5; // Credit cards have higher chargeback rates

            // Low-risk indicators (reduce risk)
            if (LifetimePurchaseCount >= 10) riskScore -= 10; // Established customer
            if (MinutesFromRegistration >= 43200) riskScore -= 10; // Account older than 30 days
            if (Player?.Alliance != null) riskScore -= 5; // Alliance member (more invested)

            riskScore = Math.Max(0, Math.Min(100, riskScore)); // Clamp to 0-100

            return riskScore switch
            {
                >= 70 => ChargebackRiskLevel.Critical,
                >= 50 => ChargebackRiskLevel.High,
                >= 30 => ChargebackRiskLevel.Medium,
                >= 15 => ChargebackRiskLevel.Low,
                _ => ChargebackRiskLevel.Minimal
            };
        }

        public PayToWinImpact AssessPayToWinImpact()
        {
            if (HasSkillBasedAlternative && SkillAlternativeUsed >= 80)
                return PayToWinImpact.Negligible;

            if (IsVipPurchase || IsDragonPurchase)
            {
                return MonthlySpendingAfter switch
                {
                    >= 500m => PayToWinImpact.High,
                    >= 200m => PayToWinImpact.Moderate,
                    >= 50m => PayToWinImpact.Low,
                    _ => PayToWinImpact.Minimal
                };
            }

            if (IsResourcePackage || IsSpeedBoostPurchase)
                return Amount >= 20m ? PayToWinImpact.Moderate : PayToWinImpact.Low;

            if (IsStealthPurchase)
                return PayToWinImpact.Minimal; // Convenience only

            return PayToWinImpact.Negligible;
        }

        // VIP Milestone Processing
        public void ProcessVipMilestone(int newVipPoints, int newSecretTier)
        {
            VipPointsBefore = VipPointsAfter;
            VipPointsAfter += newVipPoints;
            VipPointsEarned = newVipPoints;

            SecretSpendingTierBefore = SecretSpendingTierAfter;
            SecretSpendingTierAfter = newSecretTier;

            if (newSecretTier > SecretSpendingTierBefore)
            {
                UnlockedNewSecretTier = true;
                TriggeredVipMilestone = true;
                VipMilestoneReached = $"SECRET_TIER_{newSecretTier}";
            }

            // Check milestone eligibility
            if (MonthlySpendingAfter >= 100m)
                IsEligibleForMonthlyReward = true;

            if (LifetimeSpendingAfter >= 500m)
                IsEligibleForYearlyReward = true;
        }

        // Chargeback Management Methods
        public void ProcessChargeback(string reason, decimal chargebackFee = 15m)
        {
            IsChargedBack = true;
            WasChargeback = true;
            ChargebackDate = DateTime.UtcNow;
            ChargebackAt = DateTime.UtcNow;
            ChargebackReason = reason;
            ChargebackFee = chargebackFee;
            Status = PurchaseStatus.Chargeback;
            IsFraudSuspected = true;
            RequiresManualReview = true;
            ChargebackDisputeDeadline = DateTime.UtcNow.AddDays(10); // 10 days to dispute
        }

        public void DisputeChargeback()
        {
            if (!IsChargedBack)
                throw new InvalidOperationException("Cannot dispute a non-chargeback transaction");

            if (DateTime.UtcNow > ChargebackDisputeDeadline)
                throw new InvalidOperationException("Chargeback dispute deadline has passed");

            ChargebackDisputed = true;
            DisputeStatus = ChargebackDisputeStatus.UnderReview;
            RequiresManualReview = true;
        }

        public bool ShouldBlockFuturePurchases()
        {
            // Block purchases for high-risk patterns
            if (IsChargedBack && !ChargebackDisputed) return true;
            if (GetChargebackRisk() >= ChargebackRiskLevel.Critical) return true;
            if (FraudScore >= 90) return true;
            if (PurchasesInLast24Hours >= 10) return true; // Extreme velocity

            return false;
        }

        public double CalculateValuePerDollar()
        {
            if (Amount == 0) return 0;

            var valueScore = 0.0;

            // Assign value scores to different purchase types
            if (IsVipPurchase) valueScore += VipDaysAdded * 10;
            if (IsDragonPurchase) valueScore += DragonDaysAdded * 15;
            if (IsResourcePackage) valueScore += (double)TotalResourcesReceived / 10000;
            if (GoldPurchased > 0) valueScore += GoldPurchased * 0.1;
            if (IsSpeedBoostPurchase) valueScore += SpeedBoostHours * 5;

            return valueScore / (double)Amount;
        }

        public void SetDetailedPurchaseData(DetailedPurchaseData data)
        {
            DetailedPurchaseData = JsonSerializer.Serialize(data);
        }

        public DetailedPurchaseData? GetDetailedPurchaseData()
        {
            if (string.IsNullOrWhiteSpace(DetailedPurchaseData)) return null;

            try
            {
                return JsonSerializer.Deserialize<DetailedPurchaseData>(DetailedPurchaseData);
            }
            catch
            {
                return null;
            }
        }

        public void ProcessRefund(decimal refundAmount, string reason)
        {
            if (refundAmount > Amount)
                throw new InvalidOperationException("Refund amount cannot exceed purchase amount");

            IsRefunded = true;
            WasRefunded = true;
            RefundDate = DateTime.UtcNow;
            RefundedAt = DateTime.UtcNow;
            RefundAmount = refundAmount;
            RefundReason = reason;
            Status = PurchaseStatus.Refunded;
        }

        public List<string> ValidatePurchaseLog()
        {
            var errors = new List<string>();

            if (string.IsNullOrWhiteSpace(ProductId))
                errors.Add("Product ID is required");

            if (string.IsNullOrWhiteSpace(TransactionId))
                errors.Add("Transaction ID is required for chargeback protection");

            if (Amount < 0)
                errors.Add("Purchase amount cannot be negative");

            if (RefundAmount > Amount)
                errors.Add("Refund amount cannot exceed purchase amount");

            if (IsVipPurchase && VipDaysAdded <= 0)
                errors.Add("VIP purchase must add VIP days");

            if (IsDragonPurchase && DragonDaysAdded <= 0)
                errors.Add("Dragon purchase must add dragon days");

            if (IsSpeedBoostPurchase && SpeedBoostQuantity <= 0)
                errors.Add("Speed boost purchase must include boost quantity");

            if (GoldBalanceAfter < GoldBalanceBefore - GoldSpent)
                errors.Add("Gold balance calculation is incorrect");

            if (LifetimeSpendingAfter < LifetimeSpendingBefore)
                errors.Add("Lifetime spending cannot decrease");

            if (MonthlySpendingAfter < MonthlySpendingBefore)
                errors.Add("Monthly spending cannot decrease");

            if (ProcessedAt.HasValue && ProcessedAt.Value < PurchaseDate)
                errors.Add("Processed time cannot be before purchase time");

            if (VipPointsAfter < VipPointsBefore)
                errors.Add("VIP points cannot decrease from a purchase");

            if (SecretSpendingTierAfter < SecretSpendingTierBefore)
                errors.Add("Secret spending tier cannot decrease");

            return errors;
        }

        public override string ToString()
        {
            var playerName = Player?.Name ?? $"Player {PlayerId}";
            var statusText = Status switch
            {
                PurchaseStatus.Completed => "✓",
                PurchaseStatus.Pending => "⏳",
                PurchaseStatus.Failed => "✗",
                PurchaseStatus.Refunded => "↩",
                PurchaseStatus.Chargeback => "⚠",
                _ => "?"
            };

            var segmentText = $"M:{MonthlySegment:F0}/L:{LifetimeSegment:F0}";
            var riskText = IsChargebackRisk ? " 🚨" : "";
            var vipText = UnlockedNewSecretTier ? " 🎁" : "";

            return $"{statusText} {playerName}: {ProductName} - {Amount:C} ({segmentText}){riskText}{vipText}";
        }
    }

    // Supporting Classes
    public class DetailedPurchaseData
    {
        public Dictionary<string, object> PlatformData { get; set; } = new Dictionary<string, object>();
        public List<string> ItemsReceived { get; set; } = new List<string>();
        public Dictionary<string, double> BonusMultipliers { get; set; } = new Dictionary<string, double>();
        public string? SpecialOfferInfo { get; set; }
        public DateTime? OfferExpiryDate { get; set; }
        public List<string> RequirementsMet { get; set; } = new List<string>();
        public Dictionary<string, string> RiskIndicators { get; set; } = new Dictionary<string, string>();
        public Dictionary<string, int> VipMilestoneData { get; set; } = new Dictionary<string, int>();
    }

    // Enhanced Supporting Enums
    public enum PurchaseType
    {
        InAppPurchase = 1,      // Real money -> Gold/Items
        GoldSpending = 2,       // Gold -> Game items
        Subscription = 3,       // VIP/Premium subscriptions
        ResourcePurchase = 4,   // Direct resource purchases
        BoostPurchase = 5,      // Time skip and boost purchases
        CosmeticPurchase = 6    // Appearance and cosmetic items
    }

    public enum PaymentMethod
    {
        Unknown = 0,
        ApplePay = 1,
        GooglePlay = 2,
        CreditCard = 3,
        PayPal = 4,
        BankTransfer = 5,
        Cryptocurrency = 6,
        GiftCard = 7,
        PromotionalCredit = 8,
        GoldBalance = 9         // Using in-game currency
    }

    public enum PurchaseStatus
    {
        Pending = 1,
        Completed = 2,
        Failed = 3,
        Cancelled = 4,
        Refunded = 5,
        Chargeback = 6,
        UnderReview = 7,
        Blocked = 8            // Blocked due to fraud risk
    }

    public enum PurchaseCategory
    {
        Currency = 1,      // Gold purchases
        Resources = 2,     // Food/Wood/Iron/Silver/Mithril
        TimeSkip = 3,      // Speed boosts, construction boosts
        Premium = 4,       // Dragons, special items
        Subscription = 5,  // VIP, monthly subscriptions
        Convenience = 6,   // Stealth, quality of life
        Cosmetic = 7,      // Appearance items
        Other = 8
    }

    // Enhanced Customer Segmentation Enums
    public enum MonthlyCustomerSegment
    {
        MonthlyFree = 1,        // $0 this month
        MonthlyOccasional = 2,  // $1-9 this month
        MonthlySpender = 3,     // $10-49 this month
        MonthlyMinnow = 4,      // $50-199 this month
        MonthlyDolphin = 5,     // $200-499 this month
        MonthlyWhale = 6        // $500+ this month
    }

    public enum LifetimeCustomerSegment
    {
        LifetimeFree = 1,           // $0 lifetime
        LifetimeOccasional = 2,     // $1-19 lifetime
        LifetimeSpender = 3,        // $20-99 lifetime
        LifetimeMinnow = 4,         // $100-499 lifetime
        LifetimeDolphin = 5,        // $500-999 lifetime
        LifetimeWhale = 6,          // $1000-1999 lifetime
        LifetimeMegaWhale = 7       // $2000+ lifetime
    }

    public enum ChargebackRiskLevel
    {
        Minimal = 1,    // 0-14% risk score
        Low = 2,        // 15-29% risk score
        Medium = 3,     // 30-49% risk score
        High = 4,       // 50-69% risk score
        Critical = 5    // 70-100% risk score
    }

    public enum ChargebackDisputeStatus
    {
        UnderReview = 1,
        Won = 2,           // Dispute successful, chargeback reversed
        Lost = 3,          // Dispute failed, chargeback stands
        PartialWin = 4,    // Partial reversal
        Expired = 5        // Dispute deadline passed
    }

    public enum PayToWinImpact
    {
        Negligible = 1,    // No competitive advantage
        Minimal = 2,       // Very slight advantage
        Low = 3,           // Minor advantage
        Moderate = 4,      // Noticeable advantage
        High = 5,          // Significant advantage
        Extreme = 6        // Game-breaking advantage
    }

    public enum PurchaseTrend
    {
        NewSpender = 1,
        FrequentSpender = 2,    // Multiple purchases per week
        RegularSpender = 3,     // Weekly purchases
        OccasionalSpender = 4,  // Monthly purchases
        ReturnedSpender = 5,    // Returned after 1-3 months
        LongAbsentSpender = 6   // Returned after 3+ months
    }

    public enum CustomerSegment
    {
        FreeToPlay = 1,
        Occasional = 2,     // $1-10 lifetime
        Spender = 3,        // $10-100 lifetime
        Minnow = 4,         // $100-500 lifetime
        Dolphin = 5,        // $500-1000 lifetime
        Whale = 6           // $1000+ lifetime
    }
}