# Generated by Django 5.0.12 on 2025-11-28 09:18

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


def handle_data(apps, schema_editor):
    CheckedObjectIncidentRelationship = apps.get_model('wbcompliance', 'CheckedObjectIncidentRelationship')
    RiskIncident = apps.get_model('wbcompliance', 'RiskIncident')
    CheckedObjectIncidentRelationship.objects.filter(incident__isnull=True).delete()
    RiskIncident.objects.filter(checked_object_relationships__isnull=True).delete()
    RiskIncident.objects.annotate(
        is_precheck=Exists(CheckedObjectIncidentRelationship.objects.filter(incident=OuterRef("id"), rule_check__activator_id__isnull=False))
    ).filter(is_precheck=True).update(precheck=True)

class Migration(migrations.Migration):

    dependencies = [
        ('wbcompliance', '0021_riskcheck_passive_check'),
    ]

    operations = [
        migrations.AddField(
            model_name='riskincident',
            name='precheck',
            field=models.BooleanField(default=False, help_text='If true, this incident was created during a precheck evaluation', verbose_name='Precheck Incident'),
        ),
        migrations.RunSQL(sql="SET CONSTRAINTS ALL IMMEDIATE;"),
        migrations.RunPython(handle_data),
        migrations.RunSQL(sql="SET CONSTRAINTS ALL DEFERRED;"),
        migrations.AlterField(
            model_name='checkedobjectincidentrelationship',
            name='incident',
            field=models.ForeignKey(default=None, on_delete=django.db.models.deletion.CASCADE,
                                    related_name='checked_object_relationships', to='wbcompliance.riskincident'),
            preserve_default=False,
        ),
    ]
