import qrcode
from io import BytesIO
from django.core.files.base import ContentFile
from django.urls import reverse

def generate_ticket_qr_code(ticket_instance):
    if not ticket_instance or not ticket_instance.code_unique:
        return

    #
    # Le QR Code contiendra directement le chemin "/scanner/api/verify/<uuid>/"
    verification_url = reverse('scanner:api_verify', kwargs={'uuid': ticket_instance.code_unique})
    
    qr = qrcode.QRCode(
        version=1,
        error_correction=qrcode.constants.ERROR_CORRECT_L,
        box_size=10,
        border=4,
    )
    qr.add_data(verification_url)
    qr.make(fit=True)

    img = qr.make_image(fill_color="black", back_color="white")
    
    # Sauvegarder l'image en mémoire
    buffer = BytesIO()
    img.save(buffer, format='PNG')
    
    # Créer un fichier Django à partir du buffer et le sauvegarder
    file_name = f'qr_{ticket_instance.code_unique}.png'
    ticket_instance.qr_code.save(file_name, ContentFile(buffer.getvalue()), save=False)