from django.contrib.auth import get_user_model
from django.contrib.auth.signals import user_logged_in
from django.db.models.signals import post_save
from django.dispatch import receiver

from .models import CustomerProfile


@receiver(post_save, sender=get_user_model())
def create_profile(sender, instance, created, **kwargs):
    # Every account needs a profile — also accounts made before profiles existed.
    if created or not CustomerProfile.objects.filter(user=instance).exists():
        CustomerProfile.objects.get_or_create(user=instance)


@receiver(user_logged_in)
def ensure_profile(sender, request, user, **kwargs):
    CustomerProfile.objects.get_or_create(user=user)


@receiver(user_logged_in)
def link_browser_purchases(sender, request, user, **kwargs):
    """
    A reader who unlocked a magazine on this browser before having an account
    gets that access attached to their account on sign-in (they hold the secret
    access cookie, so it's theirs).
    """
    from apps.store.models import DigitalAccess
    tokens = [v for k, v in request.COOKIES.items() if k.startswith('rt_mag_')]
    if tokens:
        DigitalAccess.objects.filter(access_token__in=tokens, user__isnull=True).update(user=user)
