import uuid

from django.db import transaction

from .models import Enrollment, Order


def issue_course_access(order):
    """Issue access only for an already completed order, safely and idempotently."""
    if order.status != 'Completed':
        return None
    with transaction.atomic():
        source = 'Free' if order.course.is_free or order.amount == 0 else 'Payment'
        return Enrollment.objects.get_or_create(
            user=order.user,
            course=order.course,
            defaults={'source': source},
        )[0]


def create_pending_order(user, course):
    with transaction.atomic():
        order = Order.objects.filter(user=user, course=course, status='Pending').first()
        if order:
            order.amount = course.effective_price
            order.save(update_fields=['amount'])
            return order
        return Order.objects.create(
            user=user,
            course=course,
            amount=course.effective_price,
            status='Pending',
            transaction_id=f'PENDING-{uuid.uuid4().hex.upper()}',
        )
