from django.conf import settings
from django.db.models.signals import post_save
from django.dispatch import receiver

from users.models import User
from .models import Rider


@receiver(post_save, sender=settings.AUTH_USER_MODEL)
def create_or_update_rider_for_user(sender, instance, created, **kwargs):
    """
    Ensure a Rider record exists when a User has role 'RIDER'. This will
    create a basic Rider profile that can be completed via the Rider
    management UI. If a User's role becomes 'RIDER' later, create the
    Rider record then as well.
    """
    try:
        role = getattr(instance, 'role', None)
    except Exception:
        role = None

    if role == 'RIDER':
        # Create if missing. Don't overwrite existing rider fields.
        Rider.objects.get_or_create(
            user=instance,
            defaults={
                'full_name': f"{instance.first_name} {instance.last_name}".strip() or instance.username,
                'email': instance.email or '',
                'mobile_number': '',
            },
        )
