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

User = get_user_model()


class Sector(models.TextChoices):
    LIT = "LIT", "Litigation"
    IP  = "IP",  "Intellectual Property"
    GEN = "GEN", "General"
    FIN = "FIN", "Finance"


class GlobalCounter(models.Model):
    """
    Tracks the next index shared across all references, optionally grouped by policy.
    For simplicity we keep a single global row with scope_key='global'.
    """
    scope_key = models.CharField(max_length=20, unique=True)  # e.g. 'global'
    next_index = models.PositiveIntegerField(default=1)

    def __str__(self):
        return f"{self.scope_key} -> {self.next_index}"


class Reference(models.Model):
    STATUS_CHOICES = [
        ("ISSUED", "Issued"),
        ("RESERVED", "Reserved"),
    ]

    # Numbering + date + department (sector)
    index = models.PositiveIntegerField()
    sector = models.CharField(max_length=3, choices=Sector.choices)
    day = models.PositiveIntegerField()
    month = models.PositiveIntegerField()
    year = models.PositiveIntegerField()

    # User-entered fields at confirmation
    title = models.CharField(max_length=255)
    status = models.CharField(max_length=10, choices=STATUS_CHOICES, default="RESERVED")

    # Metadata
    assigned_to = models.ForeignKey(User, on_delete=models.PROTECT, related_name="references")
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        constraints = [
            models.UniqueConstraint(
                fields=["index", "sector", "day", "month", "year"],
                name="unique_reference_value",
            )
        ]
        ordering = ["-created_at"]

    # Column used by Django Admin + display in UI
    def ref_string(self):
        # Example: 003/RU&CO/LIT/05/09/2025
        return f"{self.index:03d}/RU&CO/{self.sector}/{self.day:02d}/{self.month:02d}/{self.year}"

    def __str__(self):
        return self.ref_string()