# Generated by Django 4.2.10 on 2024-02-19 13:48

from django.db import migrations, models
from django_scopes import scopes_disabled


def migrate_property_import_slug(apps, schema_editor):
    with scopes_disabled():
        Property = apps.get_model('cookbook', 'Property')
        Food = apps.get_model('cookbook', 'Food')

        id_slug_mapping = {}
        with scopes_disabled():
            for f in Food.objects.filter(open_data_slug__isnull=False).values('id', 'open_data_slug').all():
                id_slug_mapping[f['id']] = f['open_data_slug']

            property_update_list = []

            for p in Property.objects.filter().values('id', 'import_food_id').all():
                if p['import_food_id'] in id_slug_mapping:
                    property_update_list.append(Property(
                        id=p['id'],
                        open_data_food_slug=id_slug_mapping[p['import_food_id']]
                    ))

            Property.objects.bulk_update(property_update_list, ('open_data_food_slug',))


class Migration(migrations.Migration):
    dependencies = [
        ('cookbook', '0212_alter_property_property_amount'),
    ]

    operations = [
        migrations.AddField(
            model_name='property',
            name='open_data_food_slug',
            field=models.CharField(blank=True, default=None, max_length=128, null=True),
        ),
        migrations.RunPython(migrate_property_import_slug),
        migrations.RemoveConstraint(
            model_name='property',
            name='property_unique_import_food_per_space',
        ),
        migrations.RemoveField(
            model_name='property',
            name='import_food_id',
        ),

        migrations.AddConstraint(
            model_name='property',
            constraint=models.UniqueConstraint(fields=('space', 'property_type', 'open_data_food_slug'), name='property_unique_import_food_per_space'),
        ),
    ]
