# Generated by Django 5.2.7 on 2026-03-09 10:41

import django.db.models.deletion
from django.db import migrations, models


def populate_polymorphic_ctype(apps, schema_editor):
    ContentType = apps.get_model("contenttypes", "ContentType")
    Compound = apps.get_model("epdb", "Compound")
    CompoundStructure = apps.get_model("epdb", "CompoundStructure")

    # Update Compound records
    compound_ct = ContentType.objects.get_for_model(Compound)
    Compound.objects.filter(polymorphic_ctype__isnull=True).update(polymorphic_ctype=compound_ct)

    # Update CompoundStructure records
    compound_structure_ct = ContentType.objects.get_for_model(CompoundStructure)
    CompoundStructure.objects.filter(polymorphic_ctype__isnull=True).update(
        polymorphic_ctype=compound_structure_ct
    )


def reverse_populate_polymorphic_ctype(apps, schema_editor):
    Compound = apps.get_model("epdb", "Compound")
    CompoundStructure = apps.get_model("epdb", "CompoundStructure")

    Compound.objects.all().update(polymorphic_ctype=None)
    CompoundStructure.objects.all().update(polymorphic_ctype=None)


class Migration(migrations.Migration):
    dependencies = [
        ("contenttypes", "0002_remove_content_type_name"),
        ("epdb", "0019_remove_scenario_additional_information_and_more"),
    ]

    operations = [
        migrations.AlterModelOptions(
            name="compoundstructure",
            options={"base_manager_name": "objects"},
        ),
        migrations.AddField(
            model_name="compound",
            name="polymorphic_ctype",
            field=models.ForeignKey(
                editable=False,
                null=True,
                on_delete=django.db.models.deletion.CASCADE,
                related_name="polymorphic_%(app_label)s.%(class)s_set+",
                to="contenttypes.contenttype",
            ),
        ),
        migrations.AddField(
            model_name="compoundstructure",
            name="polymorphic_ctype",
            field=models.ForeignKey(
                editable=False,
                null=True,
                on_delete=django.db.models.deletion.CASCADE,
                related_name="polymorphic_%(app_label)s.%(class)s_set+",
                to="contenttypes.contenttype",
            ),
        ),
        migrations.RunPython(populate_polymorphic_ctype, reverse_populate_polymorphic_ctype),
    ]
