# staff/signals.py
from django.db.models.signals import post_save, pre_save
from django.dispatch import receiver
from django.contrib.auth import get_user_model
from .models import Staff

User = get_user_model()

@receiver(post_save, sender=User)
def create_staff_profile(sender, instance, created, **kwargs):
    """Create a staff profile when a user is created with staff status"""
    if created and (instance.is_staff or instance.is_superuser):
        Staff.objects.get_or_create(
            user=instance,
            defaults={
                'employee_id': f"STF{instance.id:04d}",
                'school_id': 1,
            }
        )

@receiver(post_save, sender=Staff)
def sync_user_status(sender, instance, **kwargs):
    """Sync staff active status with user account"""
    if instance.user.is_active != instance.is_active:
        instance.user.is_active = instance.is_active
        instance.user.save()

@receiver(pre_save, sender=Staff)
def set_default_employee_id(sender, instance, **kwargs):
    """Set default employee ID if not provided"""
    if not instance.employee_id:
        prefix = {
            'proprietor': 'PR',
            'head_master': 'HM',
            'head_mistress': 'HM',
            'bursar': 'BR',
            'teacher': 'TCH',
        }.get(instance.role, 'STF')
        
        last_staff = Staff.objects.filter(employee_id__startswith=prefix).order_by('-id').first()
        if last_staff:
            last_num = int(last_staff.employee_id.split('-')[-1]) if '-' in last_staff.employee_id else 1
            instance.employee_id = f"{prefix}-{last_num + 1:04d}"
        else:
            instance.employee_id = f"{prefix}-0001"