# textdocs/models.py
from django.db import models
from django.urls import reverse
from django.conf import settings

class Document(models.Model):
    """
    Represents the main document container. Stores permanent info.
    """
    author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    title = models.CharField(max_length=255)
    created_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.title

    def get_absolute_url(self):
        # The main detail page will always show the latest version
        return reverse('document_detail', kwargs={'pk': self.pk})

    @property
    def latest_version(self):
        # A helper to easily get the most recent version
        return self.versions.order_by('-version_number').first()

class DocumentVersion(models.Model):
    """
    Represents a specific version of a Document's content.
    """
    document = models.ForeignKey(Document, on_delete=models.CASCADE, related_name='versions')
    version_number = models.PositiveIntegerField()
    
    # The content fields now live here
    introduction = models.TextField()
    main_body = models.TextField()
    conclusion = models.TextField()
    
    created_at = models.DateTimeField(auto_now_add=True)
    
    class Meta:
        # Ensure a document can't have two versions with the same number
        unique_together = ('document', 'version_number')
        ordering = ['-version_number'] # Default order is newest first

    def __str__(self):
        return f"{self.document.title} (v{self.version_number})"