from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from django.urls import reverse
from courses.models import Course, Lesson
from campus.models import Enrollment, LessonProgress
from .models import Order

@login_required(login_url="users:login")
def checkout_view(request, slug):
    """
    Pantalla de Checkout. Muestra el resumen del curso y el botón para pagar con Niubiz.
    """
    course = get_object_or_404(Course, slug=slug, is_published=True)
    
    # Verificar si el usuario ya está matriculado
    if Enrollment.objects.filter(user=request.user, course=course).exists():
        messages.info(request, "Ya tienes acceso a este programa.")
        return redirect("campus:my_learning")

    price_to_pay = course.discount_price if course.discount_price else course.price

    context = {
        "course": course,
        "price_to_pay": price_to_pay,
    }
    return render(request, "pages/checkout.html", context)

@login_required(login_url="users:login")
def process_payment_view(request, slug):
    """
    Simulación del procesamiento de pago de Niubiz.
    En producción, aquí se recibiría el webhook o callback de éxito.
    """
    if request.method != "POST":
        return redirect("ecommerce:checkout", slug=slug)

    course = get_object_or_404(Course, slug=slug, is_published=True)
    price_to_pay = course.discount_price if course.discount_price else course.price

    # 1. Crear la Orden (Pagada)
    order = Order.objects.create(
        user=request.user,
        course=course,
        amount=price_to_pay,
        status="PAID",
        transaction_id=f"NIUBIZ-MOCK-{request.user.id}-{course.id}"
    )

    # 2. Generar el Enrollment
    enrollment, created = Enrollment.objects.get_or_create(user=request.user, course=course)
    
    if created:
        for module in course.modules.all():
            for lesson in module.lessons.all():
                LessonProgress.objects.get_or_create(enrollment=enrollment, lesson=lesson)
                
        messages.success(request, f"¡Pago procesado con éxito! Bienvenido a {course.title}.")
    else:
        messages.info(request, "Ya estabas matriculado en este programa.")

    return redirect("campus:my_learning")
