from decimal import Decimal

from django.conf import settings
from django.db import models


class Invoice(models.Model):
    STATUSES = [("draft", "draft"), ("issued", "issued"), ("paid", "paid"), ("cancelled", "cancelled")]

    organization = models.ForeignKey("organizations.Organization", on_delete=models.CASCADE, related_name="invoices")
    customer = models.ForeignKey("crm.Customer", on_delete=models.PROTECT, related_name="invoices")
    number = models.PositiveIntegerField(null=True, blank=True)  # assigned when issued, sequential per organization
    status = models.CharField(max_length=10, choices=STATUSES, default="draft")
    issue_date = models.DateField()
    due_date = models.DateField(null=True, blank=True)
    notes = models.TextField(blank=True, default="")
    tax_percent = models.DecimalField(max_digits=5, decimal_places=2, default=Decimal("10"))
    discount = models.BigIntegerField(default=0)
    subtotal = models.BigIntegerField(default=0)
    tax = models.BigIntegerField(default=0)
    total = models.BigIntegerField(default=0)
    created_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT, related_name="+")
    issued_at = models.DateTimeField(null=True, blank=True)
    paid_at = models.DateTimeField(null=True, blank=True)
    cancelled_at = models.DateTimeField(null=True, blank=True)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ["-created_at", "-id"]
        constraints = [
            models.UniqueConstraint(
                fields=["organization", "number"], condition=models.Q(number__isnull=False), name="unique_invoice_number_per_org"
            )
        ]


class InvoiceItem(models.Model):
    invoice = models.ForeignKey(Invoice, on_delete=models.CASCADE, related_name="items")
    description = models.CharField(max_length=300)
    quantity = models.DecimalField(max_digits=12, decimal_places=3, default=Decimal("1"))
    unit_price = models.BigIntegerField(default=0)
    line_total = models.BigIntegerField(default=0)

    class Meta:
        ordering = ["id"]
