# Generated by Django 5.1.5 on 2025-01-20 18:14

from django.core.exceptions import ObjectDoesNotExist
from django.db import IntegrityError, migrations, transaction
from edc_action_item.models import ActionItem
from edc_registration.models import RegisteredSubject
from tqdm import tqdm

from meta_consent.action_items import ConsentV1ExtensionAction


def update_missing_action_items(apps, schema_editor):
    total = RegisteredSubject.objects.all().count()
    for obj in tqdm(RegisteredSubject.objects.all(), total=total):
        try:
            ActionItem.objects.get(
                subject_identifier=obj.subject_identifier, action_type__name="consent_v1_ext"
            )
        except ObjectDoesNotExist:
            try:
                with transaction.atomic():
                    ConsentV1ExtensionAction(
                        subject_identifier=obj.subject_identifier,
                        skip_get_current_site=True,
                        site_id=obj.site_id,
                    )
            except IntegrityError:
                print(f"ERROR: Unable to create for {obj.subject_identifier}.")


class Migration(migrations.Migration):

    dependencies = [
        (
            "meta_consent",
            "0029_alter_historicalsubjectconsentv1ext_agrees_to_extension_and_more",
        ),
    ]

    operations = []
