# Generated by Django 4.0.10 on 2024-09-23 16:56

from django.conf import settings as django_settings
from django.db import migrations

DEFAULT_CONFIG = getattr(
    django_settings, "DJANGO_SITE_CONFIGS_DEFAULT_CONFIG", "default"
)


def consolidate_settings(apps, _):
    SiteConfigModel = apps.get_model("siteconfigs", "SiteConfigModel")

    qs = SiteConfigModel.objects.exclude(key=DEFAULT_CONFIG)

    # get the unique site IDs
    site_ids = qs.values_list("site_id", flat=True).distinct()

    for site_id in site_ids:

        # get the old site configs
        old_configs = qs.filter(site=site_id)

        # get or create a new site config
        new_site_conf, created = SiteConfigModel.objects.get_or_create(
            site=site_id, key=DEFAULT_CONFIG
        )

        for old_config in old_configs:
            new_site_conf.value[old_config.key] = {
                "data": old_config.value,
                "old_pk": old_config.pk,
                "deleted": old_config.deleted,
            }

        # save the updated new model
        new_site_conf.save()

        # delete the old models
        old_configs.delete()


def undo_consolidate_settings(apps, _):
    """
    This will undo the consolidation of the settings but will not restore the same PK IDs
    """
    SiteConfigModel = apps.get_model("siteconfigs", "SiteConfigModel")

    qs = SiteConfigModel.objects.filter(key=DEFAULT_CONFIG)

    # create new models for each of the keys in the value dictionary
    for site_conf in qs:
        for key, value in site_conf.value.items():
            new_conf = SiteConfigModel(
                site=site_conf.site,
                key=key,
                value=value["data"],
                id=value["old_pk"],
                deleted=value["deleted"],
            )
            new_conf.save()
        # delete the site config
        site_conf.delete()


class Migration(migrations.Migration):

    dependencies = [
        ("siteconfigs", "0002_auto_20210818_2301"),
    ]

    operations = [
        migrations.RunPython(
            consolidate_settings, reverse_code=undo_consolidate_settings
        ),
    ]
