# models.py for billing app

from django.db import models
from django.contrib.auth.models import AbstractUser
from django.utils import timezone
from django.core.validators import MinValueValidator, MaxValueValidator
from clients.models import User
import uuid


class SubscriptionPlan(models.Model): # va quedar en billing/models.py
    """Subscription plans synchronized from internal dashboard"""
    
    PLAN_TYPE_CHOICES = [
        ('basic', 'Basic'),
        ('pro', 'Pro'),
        ('enterprise', 'Enterprise'),
        ('custom', 'Custom'),
    ]
    
    # Basic plan information
    internal_plan_id = models.IntegerField(unique=True)  # ID from internal dashboard
    name = models.CharField(max_length=100)
    plan_type = models.CharField(max_length=20, choices=PLAN_TYPE_CHOICES)
    description = models.TextField(blank=True)
    
    # Pricing
    monthly_price = models.DecimalField(max_digits=10, decimal_places=2)
    annual_price = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True)
    
    # Access control - JSON structure for flexible permission management
    access_control = models.JSONField(default=dict, blank=True)
    """
    Example structure:
    {
        "date_range": {
            "from": "2024-01-01",
            "to": null  # null means current
        },
        "available_plots": ["passing_network", "heat_map", "player_stats"],
        "max_reports_per_month": 100,
        "data_delay_days": 7,  # Data is available X days after match
        "export_formats": ["pdf", "csv"],
        "api_access": false,
        "advanced_analytics": true
    }
    """
    
    # Status
    is_active = models.BooleanField(default=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    
    def __str__(self):
        return f"{self.name} ({self.get_plan_type_display()})"
    
    class Meta:
        ordering = ['plan_type', 'monthly_price']

class UserSubscription(models.Model): # va quedar en billing/models.py
    """User's active subscription"""
    
    STATUS_CHOICES = [
        ('trial', 'Trial'),
        ('active', 'Active'),
        ('paused', 'Paused'),
        ('cancelled', 'Cancelled'),
        ('expired', 'Expired'),
    ]
    
    BILLING_CYCLE_CHOICES = [
        ('monthly', 'Monthly'),
        ('annual', 'Annual'),
        ('custom', 'Custom'),
    ]
    
    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='subscriptions')
    subscription_plan = models.ForeignKey(SubscriptionPlan, on_delete=models.PROTECT)
    
    # Subscription details
    status = models.CharField(max_length=20, choices=STATUS_CHOICES, default='trial')
    billing_cycle = models.CharField(max_length=20, choices=BILLING_CYCLE_CHOICES)
    
    # Dates
    start_date = models.DateTimeField(default=timezone.now)
    end_date = models.DateTimeField(null=True, blank=True)
    trial_end_date = models.DateTimeField(null=True, blank=True)
    next_billing_date = models.DateTimeField(null=True, blank=True)
    cancelled_at = models.DateTimeField(null=True, blank=True)
    
    # Payment information
    current_price = models.DecimalField(max_digits=10, decimal_places=2)
    discount_percentage = models.DecimalField(max_digits=5, decimal_places=2, default=0)
    
    # Custom access control (overrides plan defaults)
    custom_access_control = models.JSONField(null=True, blank=True)
    
    # Metadata
    notes = models.TextField(blank=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    
    def __str__(self):
        return f"{self.user.username} - {self.subscription_plan.name} ({self.status})"
    
    def get_effective_access_control(self):
        """Merge plan access control with custom overrides"""
        base_control = self.subscription_plan.access_control.copy()
        if self.custom_access_control:
            base_control.update(self.custom_access_control)
        return base_control
    
    def is_active(self):
        return self.status == 'active' and (
            self.end_date is None or self.end_date > timezone.now()
        )
    
    class Meta:
        ordering = ['-created_at']
        indexes = [
            models.Index(fields=['user', 'status']),
            models.Index(fields=['next_billing_date']),
        ]

class Payment(models.Model): # va a quedar en billing 
    """Payment history"""
    
    PAYMENT_METHOD_CHOICES = [
        ('credit_card', 'Credit Card'),
        ('bank_transfer', 'Bank Transfer'),
        ('paypal', 'PayPal'),
        ('other', 'Other'),
    ]
    
    STATUS_CHOICES = [
        ('pending', 'Pending'),
        ('processing', 'Processing'),
        ('completed', 'Completed'),
        ('failed', 'Failed'),
        ('refunded', 'Refunded'),
    ]
    
    subscription = models.ForeignKey(UserSubscription, on_delete=models.CASCADE, related_name='payments')
    
    # Payment details
    amount = models.DecimalField(max_digits=10, decimal_places=2)
    payment_method = models.CharField(max_length=20, choices=PAYMENT_METHOD_CHOICES)
    status = models.CharField(max_length=20, choices=STATUS_CHOICES, default='pending')
    
    # Transaction information
    transaction_id = models.CharField(max_length=100, unique=True, null=True, blank=True)
    gateway_response = models.JSONField(null=True, blank=True)
    
    # Dates
    payment_date = models.DateTimeField(default=timezone.now)
    processed_at = models.DateTimeField(null=True, blank=True)
    
    # Invoice
    invoice_number = models.CharField(max_length=50, unique=True, null=True, blank=True)
    invoice_pdf = models.FileField(upload_to='invoices/', null=True, blank=True)
    
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    
    def __str__(self):
        return f"Payment {self.invoice_number or self.id} - {self.amount}"
    
    class Meta:
        ordering = ['-payment_date']
