# Generated by Django 3.2.20 on 2023-11-06 18:56

from django.apps.registry import Apps
from django.db import migrations, models


def unique_school_names(apps: Apps, *args):
    School = apps.get_model("common", "School")

    def get_school_name(school_name: str, school_name_number: int):
        return f"{school_name} {school_name_number}"

    school_values = School.objects.values("name").annotate(name_count=models.Count("name")).filter(name_count__gt=1)
    for school_value in school_values:
        school_name = school_value["name"]
        school_name_number = 1

        schools = list(School.objects.filter(name=school_name).order_by("id"))
        for index in range(1, len(schools)):
            school = schools[index]

            school.name = get_school_name(school_name, school_name_number)
            while School.objects.filter(name=school.name).exists():
                school_name_number += 1
                school.name = get_school_name(school_name, school_name_number)

            school.save()


class Migration(migrations.Migration):
    dependencies = [
        ("common", "0047_delete_school_postcode"),
    ]

    operations = [
        migrations.RunPython(code=unique_school_names, reverse_code=migrations.RunPython.noop),
        migrations.AlterField(
            model_name="school",
            name="name",
            field=models.CharField(max_length=200, unique=True),
        ),
    ]
