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

class Progression(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='progress')
    course = models.ForeignKey('courses.Course', on_delete=models.CASCADE, related_name='user_progress')
    completed_lessons = models.ManyToManyField('courses.Lesson', blank=True, related_name='completed_by')
    last_viewed_lesson = models.ForeignKey('courses.Lesson', on_delete=models.SET_NULL, null=True, blank=True, related_name='last_viewed_by')
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        unique_together = ('user', 'course')
        verbose_name = "Progression du cours"

    def __str__(self):
        return f"{self.user} - {self.course.name}"

    @property
    def percent_completed(self):
        from courses.models import Lesson
        total_lessons = Lesson.objects.filter(module__course=self.course).count()
        if total_lessons == 0:
            return 0

        completed_lessons = self.completed_lessons.count()

        return int((completed_lessons / total_lessons) * 100)