from django.db import models
from django.contrib.auth import get_user_model
from plans.models import Plan


User = get_user_model()


class Domain(models.Model):
    STATUS_PENDING = 'pending_dns'
    STATUS_ACTIVE = 'active'
    STATUS_SUSPENDED = 'suspended'
    STATUS_DELETED = 'deleted'
    STATUS_CHOICES = [
        (STATUS_PENDING, '等待DNS配置'),
        (STATUS_ACTIVE, '正常'),
        (STATUS_SUSPENDED, '暂停'),
        (STATUS_DELETED, '已删除'),
    ]

    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='domains')
    name = models.CharField(max_length=253, unique=True)
    status = models.CharField(max_length=20, choices=STATUS_CHOICES, default=STATUS_PENDING)
    current_plan = models.ForeignKey(Plan, null=True, blank=True, on_delete=models.SET_NULL)
    current_cycle_start = models.DateField(null=True, blank=True)
    current_cycle_end = models.DateField(null=True, blank=True)
    cname_targets = models.JSONField(default=dict, blank=True)
    origin_config = models.JSONField(default=dict, blank=True)
    edge_server_id = models.BigIntegerField(null=True, blank=True)

    # overrides (optional)
    extra_free_traffic_gb_current_cycle = models.PositiveIntegerField(default=0)
    custom_overage_price_per_gb = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True)
    custom_features = models.JSONField(default=dict, blank=True)

    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        verbose_name = '域名'
        verbose_name_plural = '域名'
        indexes = [
            models.Index(fields=['user', 'name']),
            models.Index(fields=['status']),
        ]

    def __str__(self):
        return self.name


class DomainTrafficDaily(models.Model):
    domain = models.ForeignKey(Domain, on_delete=models.CASCADE, related_name='daily_traffic')
    day = models.DateField()
    bytes = models.BigIntegerField(default=0)
    peak_bandwidth_mbps = models.FloatField(default=0)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        verbose_name = '域名日流量'
        verbose_name_plural = '域名日流量'
        unique_together = ('domain', 'day')
        indexes = [
            models.Index(fields=['domain', 'day']),
        ]

# Create your models here.
