# Generated by Django 3.2.14 on 2022-07-11 15:10

from django.db import migrations

from zgw_consumers.constants import APITypes
from zgw_consumers.service import Service as _Service


def migrate_notifications_config_forwards(apps, _):
    NotificationsConfig = apps.get_model("notifications_api_common.NotificationsConfig")
    Service = apps.get_model("zgw_consumers.Service")

    config, _ = NotificationsConfig.objects.get_or_create()

    direct_match = _Service.get_service(config.api_root)
    if direct_match:
        config.notifications_api_service = Service.objects.get(pk=direct_match.pk)
    else:
        service = Service.objects.filter(api_type=APITypes.nrc).first()
        config.notifications_api_service = service
    config.save()


def migrate_notifications_config_backwards(apps, _):
    NotificationsConfig = apps.get_model("notifications_api_common.NotificationsConfig")

    config, _ = NotificationsConfig.objects.get_or_create()
    config.api_root = getattr(config.notifications_api_service, "api_root", "")


class Migration(migrations.Migration):

    dependencies = [
        (
            "notifications_api_common",
            "0002_notificationsconfig_notifications_api_service",
        ),
    ]

    operations = [
        migrations.RunPython(
            migrate_notifications_config_forwards,
            migrate_notifications_config_backwards,
        )
    ]
