# Generated by Django 6.0 on 2025-01-27 22:43
from django.apps import apps as django_apps
from django.core.exceptions import ObjectDoesNotExist
from django.db import migrations
from edc_facility.utils import get_health_facility_model_cls
from edc_sites.site import sites as site_sites
from edc_sites.utils import get_site_model_cls

from meta_lists.list_data import list_data


def update_healthfacility(apps, schema_editor):
    health_facility_model_cls = get_health_facility_model_cls()

    name, display_name = list_data.get("edc_facility.healthfacilitytypes")[0]
    try:
        health_facility_type = django_apps.get_model(
            "edc_facility.healthfacilitytypes"
        ).objects.get(name=name)
    except ObjectDoesNotExist:
        health_facility_type = django_apps.get_model(
            "edc_facility.healthfacilitytypes"
        ).objects.create(name=name, display_name=display_name)

    for site_obj in get_site_model_cls().objects.all():
        single_site = site_sites.get(site_obj.id)
        health_facility_model_cls.objects.create(
            name=single_site.name,
            title=single_site.title,
            mon=True,
            tue=True,
            wed=True,
            thu=True,
            fri=True,
            sat=False,
            sun=False,
            site_id=site_obj.id,
            health_facility_type=health_facility_type,
        )


class Migration(migrations.Migration):

    dependencies = [
        ("meta_lists", "0018_missedreferralreasons"),
    ]

    operations = [migrations.RunPython(update_healthfacility)]
