"""
Core models for the Dubai Analytics Platform.
"""
from django.db import models
from django.contrib.auth.models import AbstractUser
from django.utils import timezone
import uuid


class TimeStampedModel(models.Model):
    """Abstract base class with self-updating created and modified fields."""
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        abstract = True


# User model is defined in apps.users.models


class APIUsage(TimeStampedModel):
    """Track API usage for billing and rate limiting."""
    user = models.ForeignKey('users.User', on_delete=models.CASCADE, related_name='api_usage')
    endpoint = models.CharField(max_length=255)
    method = models.CharField(max_length=10)
    status_code = models.IntegerField()
    response_time_ms = models.IntegerField()
    ip_address = models.GenericIPAddressField()
    user_agent = models.TextField(blank=True)
    
    class Meta:
        db_table = 'api_usage'
        indexes = [
            models.Index(fields=['user', 'created_at']),
            models.Index(fields=['endpoint', 'created_at']),
        ]

    def __str__(self):
        return f"{self.user.email} - {self.endpoint} - {self.created_at}"


class APIRateLimit(TimeStampedModel):
    """Rate limiting configuration per user tier."""
    subscription_type = models.CharField(
        max_length=20,
        choices=[
            ('free', 'Free'),
            ('paid', 'Paid'),
            ('premium', 'Premium'),
        ],
        unique=True
    )
    requests_per_minute = models.IntegerField(default=60)
    requests_per_hour = models.IntegerField(default=1000)
    requests_per_day = models.IntegerField(default=10000)
    
    class Meta:
        db_table = 'api_rate_limits'

    def __str__(self):
        return f"{self.subscription_type} - {self.requests_per_minute}/min"


class SystemConfiguration(TimeStampedModel):
    """System-wide configuration settings."""
    key = models.CharField(max_length=100, unique=True)
    value = models.TextField()
    description = models.TextField(blank=True)
    is_encrypted = models.BooleanField(default=False)
    
    class Meta:
        db_table = 'system_configuration'

    def __str__(self):
        return f"{self.key}: {self.value[:50]}..."


class AuditLog(TimeStampedModel):
    """Audit logging for security and compliance."""
    user = models.ForeignKey('users.User', on_delete=models.SET_NULL, null=True, blank=True)
    action = models.CharField(max_length=100)
    resource_type = models.CharField(max_length=50)
    resource_id = models.CharField(max_length=100, blank=True)
    details = models.JSONField(default=dict)
    ip_address = models.GenericIPAddressField()
    user_agent = models.TextField(blank=True)
    
    class Meta:
        db_table = 'audit_logs'
        indexes = [
            models.Index(fields=['user', 'created_at']),
            models.Index(fields=['action', 'created_at']),
            models.Index(fields=['resource_type', 'resource_id']),
        ]

    def __str__(self):
        return f"{self.user.email if self.user else 'System'} - {self.action} - {self.created_at}"

