from django.db import models
from django.conf import settings
from credit_scoring.models import CreditApplication
import uuid
import os

def application_document_path(instance, filename):
    """Generate file path for uploaded documents"""
    return f'documents/{instance.credit_application.application_number}/{instance.document_type}/{filename}'

class Document(models.Model):
    DOCUMENT_TYPES = [
        ('BEE', 'BEE Certificate'),
        ('TAX', 'Tax Clearance Certificate'),
        ('FINANCIAL', 'Financial Statements (3 years)'),
        ('ID', 'Director ID Documents'),
        ('CIPC', 'CIPC Registration Document'),
        ('BANKING', 'Banking Details Confirmation'),
        ('INVOICE', 'Sample Invoice'),
        ('PO', 'Purchase Order'),
        ('CONTRACT', 'Service Contract'),
    ]
    
    STATUS_CHOICES = [
        ('PENDING', 'Pending Verification'),
        ('VERIFIED', 'Verified'),
        ('REJECTED', 'Rejected'),
        ('EXPIRED', 'Expired'),
    ]
    
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    credit_application = models.ForeignKey(CreditApplication, on_delete=models.CASCADE, related_name='documents')
    document_type = models.CharField(max_length=20, choices=DOCUMENT_TYPES)
    file = models.FileField(upload_to=application_document_path)
    filename = models.CharField(max_length=255)
    file_size = models.IntegerField(help_text="File size in bytes")
    status = models.CharField(max_length=20, choices=STATUS_CHOICES, default='PENDING')
    verified_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=True)
    verified_at = models.DateTimeField(null=True, blank=True)
    rejection_reason = models.TextField(blank=True)
    uploaded_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    
    class Meta:
        db_table = 'documents'
        ordering = ['-uploaded_at']
    
    def save(self, *args, **kwargs):
        if self.file and not self.filename:
            self.filename = self.file.name
            self.file_size = self.file.size
        super().save(*args, **kwargs)
    
    def __str__(self):
        return f"{self.get_document_type_display()} - {self.credit_application.application_number}"