
from django.db import models
from customers.models import Customer

class NetworkDevice(models.Model):
    DEVICE_TYPE_CHOICES = [
        ('router', 'Router'),
        ('switch', 'Switch'),
        ('access_point', 'Access Point'),
        ('server', 'Server'),
    ]
    
    name = models.CharField(max_length=100)
    device_type = models.CharField(max_length=20, choices=DEVICE_TYPE_CHOICES)
    ip_address = models.GenericIPAddressField()
    mac_address = models.CharField(max_length=17, blank=True)
    location = models.CharField(max_length=200, blank=True)
    is_active = models.BooleanField(default=True)
    created_at = models.DateTimeField(auto_now_add=True)
    
    def __str__(self):
        return f"{self.name} ({self.ip_address})"

class ClientConnection(models.Model):
    customer = models.ForeignKey(Customer, on_delete=models.CASCADE, related_name='connections')
    username = models.CharField(max_length=100)  # PPPoE/Hotspot username
    password = models.CharField(max_length=100)  # PPPoE/Hotspot password
    ip_address = models.GenericIPAddressField(null=True, blank=True)
    mac_address = models.CharField(max_length=17, blank=True)
    
    # Connection status
    is_active = models.BooleanField(default=True)
    is_online = models.BooleanField(default=False)
    last_seen = models.DateTimeField(null=True, blank=True)
    
    # Usage statistics
    bytes_uploaded = models.BigIntegerField(default=0)
    bytes_downloaded = models.BigIntegerField(default=0)
    session_time = models.DurationField(null=True, blank=True)
    
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    
    def __str__(self):
        return f"{self.customer.full_name} - {self.username}"
    
    @property
    def total_usage_gb(self):
        total_bytes = self.bytes_uploaded + self.bytes_downloaded
        return round(total_bytes / (1024**3), 2)  # Convert to GB

class ConnectionLog(models.Model):
    connection = models.ForeignKey(ClientConnection, on_delete=models.CASCADE, related_name='logs')
    action = models.CharField(max_length=50)  # connect, disconnect, suspend, reactivate
    timestamp = models.DateTimeField(auto_now_add=True)
    details = models.TextField(blank=True)
    
    def __str__(self):
        return f"{self.connection.username} - {self.action} at {self.timestamp}"
    
    class Meta:
        ordering = ['-timestamp']
