import io
import qrcode
from django.core.files.base import ContentFile


def generate_qr_code_for_user(user):
    """
    Generate a QR code containing the user's membership_id.
    Returns a ContentFile ready to be saved to the user's qr_code field.
    """
    qr = qrcode.QRCode(
        version=1,
        error_correction=qrcode.constants.ERROR_CORRECT_H,
        box_size=10,
        border=4,
    )

    # Data embedded in the QR code
    qr_data = f"APECB-MEMBER:{user.membership_id}"
    qr.add_data(qr_data)
    qr.make(fit=True)

    img = qr.make_image(fill_color="black", back_color="white")

    # Save to a bytes buffer
    buffer = io.BytesIO()
    img.save(buffer, format="PNG")
    buffer.seek(0)

    filename = f"qr_{user.membership_id}.png"
    return ContentFile(buffer.read(), name=filename)
