# Generated by Django 2.2.24 on 2021-10-28 18:15

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


def populate_project(apps, schema_editor):
    MetricThreshold = apps.get_model('core', 'MetricThreshold')
    for threshold in MetricThreshold.objects.filter().prefetch_related('environment__project').all():
        threshold.project = threshold.environment.project
        threshold.save()


def reverse_empty_envs(apps, schema_editor):
    MetricThreshold = apps.get_model('core', 'MetricThreshold')
    thresholds = MetricThreshold.objects.filter(environment__isnull=True, project__isnull=False).prefetch_related('project').all()
    for threshold in thresholds:
        threshold.delete()

        for env in threshold.project.environments.all():
            MetricThreshold.objects.create(
                name=threshold.name,
                is_higher_better=threshold.is_higher_better,
                environment=env,
                value=threshold.value,
                project=threshold.project)


class Migration(migrations.Migration):

    dependencies = [
        ('core', '0159_nullable_metricthreshold_value'),
    ]

    operations = [
        migrations.AddField(
            model_name='metricthreshold',
            name='project',
            field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='core.Project', default=None, null=True),
        ),
        migrations.AlterUniqueTogether(
            name='metricthreshold',
            unique_together={('project', 'environment', 'name')},
        ),
        migrations.AlterField(
            model_name='metricthreshold',
            name='environment',
            field=models.ForeignKey(blank=True, null=True, default=None, on_delete=django.db.models.deletion.CASCADE, to='core.Environment'),
        ),
        migrations.RunPython(populate_project, reverse_empty_envs),
        migrations.AlterField(
            model_name='metricthreshold',
            name='project',
            field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='thresholds', to='core.Project'),
        ),
    ]
