from django.db import models
import uuid

class Certificate(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    course = models.ForeignKey('course.AllCourse', on_delete=models.CASCADE, related_name='certificates')
    student = models.ForeignKey('subscriptions.Profile', on_delete=models.CASCADE, related_name='certificates')
    certificate_number = models.CharField(max_length=255, null=True, blank=True, unique=True)
    certificate_date = models.DateField(auto_now_add=True)
    exam_score = models.DecimalField(max_digits=5, decimal_places=2)
    certificate_url = models.URLField(blank=True, null=True)
    is_active = models.BooleanField(default=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    def __str__(self):
        return f"{self.student.name} - {self.course.name}"
    
    class Meta:
        ordering = ['-certificate_date']
        unique_together = ['course', 'student']

    def generate_certificate_number(self):
        import uuid
        return f"MKAR-CERT-{str(uuid.uuid4())[:10].upper()}"

    def save(self, *args, **kwargs):
        if not self.certificate_number:
            self.certificate_number = self.generate_certificate_number()
        
        # Save first to get the ID
        super().save(*args, **kwargs)
        
        # Update certificate_url if not set
        if not self.certificate_url:
            self.certificate_url = f"/api/academy/certificates/{self.id}/download/"
            super().save(update_fields=['certificate_url'])