# Generated by Django 5.1 on 2025-04-03 12:29

from django.db import migrations
from ..utils.licence_validator import LicenseValidator

def clean_license_ids(apps, schema_editor):
    # Get the historical model
    CustomUser = apps.get_model('tournaments', 'CustomUser')

    # Query all users
    users = CustomUser.objects.all()

    for user in users:
        if user.licence_id:
            # Clean up logic - examples:
            # 1. Strip whitespace
            cleaned_id = user.licence_id.strip()
            cleaned_id = cleaned_id.replace(' ', '').strip().upper()
            last_char = cleaned_id[-1] if cleaned_id else ''
            ends_with_non_alpha = not last_char.isalpha()
            if ends_with_non_alpha:
                key = LicenseValidator.get_computed_license_key(cleaned_id)
                if key:
                    cleaned_id += key.upper()


            # Save the cleaned value
            if cleaned_id != user.licence_id:
                user.licence_id = cleaned_id
                user.save()

def reverse_migration(apps, schema_editor):
    # Reversing this migration isn't generally needed for data cleanup
    pass


class Migration(migrations.Migration):

    dependencies = [
        ('tournaments', '0114_purchase_creation_date_purchase_last_update_and_more'),
    ]

    operations = [
        migrations.RunPython(clean_license_ids, reverse_migration),
    ]
