# Generated by Django 5.2.1 on 2026-04-08 14:26

from django.db import migrations
import uuid
from django.utils import timezone


def populate_generation_codes(apps, schema_editor):
    """Populate generation_code for existing UserProfile records"""
    UserProfile = apps.get_model('appauthentication', 'UserProfile')
    
    profiles_without_code = UserProfile.objects.filter(generation_code__isnull=True)
    count = profiles_without_code.count()
    
    if count > 0:
        print(f"Generating codes for {count} existing user profiles...")
        for profile in profiles_without_code:
            profile.generation_code = f"ESS-KBY-{timezone.now().strftime('%d%m%Y')}-{uuid.uuid4().hex[:8].upper()}"
            profile.save()
        print(f"✓ Successfully generated {count} unique codes")
    else:
        print("No profiles need generation codes")


def reverse_codes(apps, schema_editor):
    """Reverse migration - set all generation_codes to None"""
    UserProfile = apps.get_model('appauthentication', 'UserProfile')
    UserProfile.objects.all().update(generation_code=None)


class Migration(migrations.Migration):

    dependencies = [
        ('appauthentication', '0011_userprofile_generation_code'),
    ]

    operations = [
        migrations.RunPython(populate_generation_codes, reverse_codes),
    ]
