from django.shortcuts import get_object_or_404, render
from django.db.models import Q
from .models import Category, Course

def catalog_view(request):
    """
    Catálogo general de cursos (/cursos/) con soporte de búsqueda e interfaz moderna.
    """
    categories = Category.objects.all()
    courses = Course.objects.filter(is_published=True).select_related("category")

    category_slug = request.GET.get("category")
    query = request.GET.get("q")

    if category_slug:
        courses = courses.filter(category__slug=category_slug)
    if query:
        courses = courses.filter(
            Q(title__icontains=query)
            | Q(short_description__icontains=query)
            | Q(iso_standard__icontains=query)
            | Q(description__icontains=query)
        )

    context = {
        "categories": categories,
        "courses": courses,
        "selected_category": category_slug,
        "search_query": query or "",
    }

    # Si es una petición HTMX, devolver solo el partial de la grilla de cursos
    if request.headers.get("HX-Request"):
        return render(request, "partials/catalog_grid.html", context)

    return render(request, "pages/catalog.html", context)


def course_detail_view(request, slug):
    """
    Temario, objetivos y detalle completo del curso (/curso/<slug>/).
    """
    course = get_object_or_404(Course.objects.prefetch_related("modules__lessons"), slug=slug, is_published=True)

    is_enrolled = False
    enrollment = None
    first_lesson = None

    first_module = course.modules.first()
    if first_module:
        first_lesson = first_module.lessons.first()

    if request.user.is_authenticated:
        from campus.models import Enrollment
        enrollment = Enrollment.objects.filter(user=request.user, course=course).first()
        is_enrolled = enrollment is not None

    context = {
        "course": course,
        "is_enrolled": is_enrolled,
        "enrollment": enrollment,
        "first_lesson": first_lesson,
    }
    return render(request, "pages/course_detail.html", context)
