"""HR signals:
- post_save User → auto-create Employee stub (so request.user always has .employee)
- post_save Employee → bridge to Contact (canonical Person table)
"""

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

from .models import Employee


def _generate_employee_id(user) -> str:
    suffix = str(user.id).replace("-", "")[-8:].upper()
    return f"EMP-{suffix}"


@receiver(post_save, sender=settings.AUTH_USER_MODEL)
def ensure_employee_for_user(sender, instance, created, **kwargs):
    if not created:
        return
    if Employee.objects.filter(user=instance).exists():
        return
    Employee.objects.create(
        user=instance,
        employee_id=_generate_employee_id(instance),
        position="Unassigned",
        department="Unassigned",
        hire_date=timezone.now().date(),
    )


@receiver(post_save, sender=Employee)
def ensure_contact_for_employee(sender, instance, created, **kwargs):
    from apps.contacts.models import Contact

    user = instance.user
    if not user:
        return

    contact = Contact.objects.filter(user=user).first()
    if contact is None:
        contact = Contact.objects.filter(email__iexact=user.email).first() if user.email else None
        if contact is not None and contact.user_id is None:
            contact.user = user
            contact.save(update_fields=["user"])

    if contact is None:
        full_name = user.get_full_name() or user.username or user.email
        Contact.objects.create(
            user=user,
            name=full_name,
            email=user.email or "",
            phone=getattr(user, "phone", "") or "",
            type="individual",
            position=instance.position or "",
        )
