# api/signals.py (full replacement or update your existing file)

from django.apps import AppConfig
from django.db.models.signals import post_migrate
from django.dispatch import receiver
from .models import CustomUser, Grade  # Adjust imports as needed

@receiver(post_migrate)
def create_defaults(sender, **kwargs):
    if sender.name != 'api':  # Only run for your 'api' app to avoid unnecessary triggers
        return

    # Define default users with roles and passwords (use a secure default; override in settings.py if needed)
    default_password = 'Bethel2025!'  # Or getattr(settings, 'DEFAULT_TEMP_PASSWORD', 'SecureDefault123!')
    users = [
        {'email': 'superadmin@bethel.school', 'role': 'super_admin', 'first_name': 'Super', 'last_name': 'Admin'},
        {'email': 'admin@bethel.school', 'role': 'admin', 'first_name': 'Admin', 'last_name': ''},
       
    ]

    for user_data in users:
        user, created = CustomUser.objects.get_or_create(
            username=user_data['email'],
            email=user_data['email'],
            defaults={
                'first_name': user_data['first_name'],
                'last_name': user_data['last_name'],
                'role': user_data['role'],
                'is_active': True,
                'must_change_password': True,  # If you have this field
            }
        )
        if created:
            user.set_password(default_password)  # Hash the password properly
            user.save()
            print(f"Created default user: {user_data['email']} with password: {default_password} (change immediately!)")
        else:
            print(f"Verified existing default user: {user_data['email']}")

    # Grades creation (assuming based on your logs)
    grades = [
        {'code': 'GRADE1', 'name': 'Grade 1'},
        {'code': 'GRADE2', 'name': 'Grade 2'},
        {'code': 'GRADE3', 'name': 'Grade 3'},
        {'code': 'GRADE4', 'name': 'Grade 4'},
        {'code': 'GRADE5', 'name': 'Grade 5'},
        {'code': 'GRADE6', 'name': 'Grade 6'},
        {'code': 'GRADE7', 'name': 'Grade 7(Junior sec)'},
        {'code': 'GRADE8', 'name': 'Grade 8(Junior sec)'},
        {'code': 'GRADE9', 'name': 'Grade 9(Junior sec)'},
    ]
    for grade_data in grades:
        grade, created = Grade.objects.get_or_create(
            code=grade_data['code'],
            defaults={'name': grade_data['name']}
        )
        print("Default grade created or verified.")