# Generated by Django 2.2.10 on 2020-03-05 09:17

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


def set_family(apps, schema_editor):
    Case = apps.get_model("caluma_workflow", "Case")
    HistoricalCase = apps.get_model("caluma_workflow", "HistoricalCase")
    db_alias = schema_editor.connection.alias

    orphan_cases = Case.objects.using(db_alias).filter(family__isnull=True)
    orphan_historical_cases = HistoricalCase.objects.using(db_alias).filter(
        family__isnull=True
    )

    for case in orphan_cases:
        family = case
        while hasattr(family, "parent_work_item"):
            family = case.parent_work_item.case
        case.family = family

    Case.objects.using(db_alias).bulk_update(orphan_cases, ["family"])

    for case in orphan_historical_cases:
        # for historical cases, it's possible that the original case doesn't exist
        # anymore. In those cases we set the family to the id of the (now non-existent)
        # original case.
        family = case
        try:
            family = Case.objects.using(db_alias).get(pk=family.id).family
        except Case.DoesNotExist:
            pass
        case.family_id = family.id

    HistoricalCase.objects.using(db_alias).bulk_update(
        orphan_historical_cases, ["family"]
    )


class Migration(migrations.Migration):

    dependencies = [("caluma_workflow", "0019_slugfield_length")]

    operations = [
        migrations.AddField(
            model_name="case",
            name="family",
            field=models.ForeignKey(
                help_text="Family id which case belongs to.",
                null=True,
                on_delete=django.db.models.deletion.CASCADE,
                related_name="+",
                to="caluma_workflow.Case",
            ),
        ),
        migrations.AddField(
            model_name="historicalcase",
            name="family",
            field=models.ForeignKey(
                blank=True,
                db_constraint=False,
                help_text="Family id which case belongs to.",
                null=True,
                on_delete=django.db.models.deletion.DO_NOTHING,
                related_name="+",
                to="caluma_workflow.Case",
            ),
        ),
        migrations.RunPython(set_family, migrations.RunPython.noop),
    ]
