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


User = get_user_model()


class Invoice(models.Model):
    STATUS_UNPAID = 'unpaid'
    STATUS_PAID = 'paid'
    STATUS_CANCELLED = 'cancelled'
    STATUS_CHOICES = [
        (STATUS_UNPAID, '未支付'),
        (STATUS_PAID, '已支付'),
        (STATUS_CANCELLED, '已取消'),
    ]

    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='invoices')
    period_start = models.DateField()
    period_end = models.DateField()
    amount_plan_total = models.DecimalField(max_digits=12, decimal_places=2, default=0)
    amount_overage_total = models.DecimalField(max_digits=12, decimal_places=2, default=0)
    amount_adjustment = models.DecimalField(max_digits=12, decimal_places=2, default=0)
    amount_total = models.DecimalField(max_digits=12, decimal_places=2, default=0)
    status = models.CharField(max_length=20, choices=STATUS_CHOICES, default=STATUS_UNPAID)
    created_at = models.DateTimeField(auto_now_add=True)
    paid_at = models.DateTimeField(null=True, blank=True)

    class Meta:
        verbose_name = '账单'
        verbose_name_plural = '账单'
        ordering = ['-period_end']


class InvoiceItem(models.Model):
    invoice = models.ForeignKey(Invoice, related_name='items', on_delete=models.CASCADE)
    domain = models.ForeignKey('domains.Domain', on_delete=models.SET_NULL, null=True, blank=True)
    description = models.CharField(max_length=200)
    quantity = models.DecimalField(max_digits=12, decimal_places=3, default=0)  # GB
    unit_price = models.DecimalField(max_digits=12, decimal_places=2, default=0)
    amount = models.DecimalField(max_digits=12, decimal_places=2, default=0)

    class Meta:
        verbose_name = '账单项'
        verbose_name_plural = '账单项'

# Create your models here.
