# Generated by Django 5.1.2 on 2025-01-15 17:25

from django.db import IntegrityError, migrations, transaction
from edc_constants.constants import OTHER
from edc_utils import get_utcnow

from meta_lists.models import OffstudyReasons
from meta_prn.action_items import OffStudyMedicationAction
from meta_prn.models import EndOfStudy


def update_offstudy_reason(apps, schema_editor):
    """Datafix: Correct offstudy_reason from `other` to 'diabetes'
    based on the `other_offstudy_reason`. These four subjects were
    taken off study before 'diabetes' was an option.

    Create missing OffStudyMedicationAction if needed.
    """
    subject_identifiers = [
        "105-60-0029-0",
        "105-60-0106-6",
        "105-60-0145-4",
        "105-60-0166-0",
    ]
    other_reason_obj = OffstudyReasons.objects.get(name=OTHER)
    diabetes_reason_obj = OffstudyReasons.objects.get(name="diabetes")
    for obj in EndOfStudy.objects.filter(
        subject_identifier__in=subject_identifiers,
        offstudy_reason=other_reason_obj,
        other_offstudy_reason__icontains="THE CLIENT HAS DEVELOPED DIABETES",
    ):
        try:
            with transaction.atomic():
                OffStudyMedicationAction(
                    subject_identifier=obj.subject_identifier,
                    skip_get_current_site=True,
                    site_id=obj.site_id,
                )
        except IntegrityError:
            pass

        obj.offstudy_reason = diabetes_reason_obj
        obj.comment = obj.other_offstudy_reason
        obj.comment = obj.comment + " [datafix: 0061_auto_20250115_2025]"
        obj.other_offstudy_reason = ""
        obj.modified = get_utcnow()
        obj.user_modified = "erikvw"
        obj.save()


class Migration(migrations.Migration):

    dependencies = [
        ("meta_prn", "0060_alter_onschedule_managers_and_more"),
    ]

    operations = [migrations.RunPython(update_offstudy_reason)]
