import requests
from django.conf import settings
from django.core.exceptions import ValidationError

class TurnstileMixin:
    """
    Mixin to handle Cloudflare Turnstile validation.
    """
    def validate_turnstile(self, request):
        """
        Validate the Turnstile response token.
        """
        token = request.POST.get('cf-turnstile-response')
        if not token:
            raise ValidationError('Please complete the Turnstile challenge.')

        # Verify the token with Cloudflare
        data = {
            'secret': settings.TURNSTILE_SECRET_KEY,
            'response': token,
            'remoteip': request.META.get('REMOTE_ADDR'),
        }

        response = requests.post(settings.TURNSTILE_VERIFY_URL, data=data)
        result = response.json()

        if not result.get('success'):
            raise ValidationError('Turnstile validation failed. Please try again.')
