from django.shortcuts import render, get_object_or_404
import json
from django.http import JsonResponse
from django.views.decorators.http import require_POST
from django.contrib.auth.decorators import login_required
from progression.models import Progression
from courses.models import Lesson

@login_required
@require_POST
def toggle_lesson_completion(request):
    data = json.loads(request.body)
    lesson_id = data.get('lesson_id')

    lesson = get_object_or_404(Lesson, id=lesson_id)
    # On remonte au cours via le module (Lesson -> Module -> Course)
    course = lesson.module.course

    # On récupère ou crée la progression
    progression, created = Progression.objects.get_or_create(
        user=request.user,
        course=course
    )

    # La logique du Toggle
    if lesson in progression.completed_lessons.all():
        progression.completed_lessons.remove(lesson)
        is_completed = False
    else:
        progression.completed_lessons.add(lesson)
        is_completed = True

        # Mise à jour de la dernière leçon vue
        progression.last_viewed_lesson = lesson
        progression.save()

    return JsonResponse({
        'status': 'success',
        'is_completed': is_completed,
        'new_percent': progression.percent_completed
    })