from .models import AffiliateProfile

class AffiliateTrackingMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        ref_code = request.GET.get('ref', '').strip()

        if ref_code:
            affiliate = AffiliateProfile.objects.filter(
                affiliate_code__iexact=ref_code,
                status='approved',
                is_active=True
            ).first()

            if affiliate:
                request.session['affiliate_code'] = affiliate.affiliate_code
                request.session['affiliate_id'] = affiliate.id
                request._affiliate_to_set = affiliate  # pass to response stage

        response = self.get_response(request)

        # Set a dedicated cookie on the response
        if hasattr(request, '_affiliate_to_set'):
            aff = request._affiliate_to_set
            response.set_cookie(
                'affiliate_code',
                aff.affiliate_code,
                max_age=60 * 60 * 24 * 30,  # 30 days
                httponly=True,
                samesite='Lax',
            )

        return response