# Generated by Django 3.2.20 on 2023-07-25 15:46

from __future__ import annotations

from typing import TYPE_CHECKING

from django.db import migrations, models

from ..constants import poicategory

if TYPE_CHECKING:
    from django.apps.registry import Apps
    from django.db.backends.base.schema import BaseDatabaseSchemaEditor


# pylint: disable=unused-argument
def check_and_update_poicategory(
    apps: Apps, schema_editor: BaseDatabaseSchemaEditor
) -> None:
    """
    This function checks whether the default POI category "Other" exists and creates it if not.
    It checks furthermore whether each location has a category and assigns the default category if not.
    """
    Language = apps.get_model("cms", "Language")
    if not (default_language := Language.objects.first()):
        # If no languages exists, we can assume that also no POIs exist
        return

    POICategory = apps.get_model("cms", "POICategory")
    POI = apps.get_model("cms", "POI")

    if not (
        default_category := POICategory.objects.filter(icon=poicategory.OTHER).first()
    ):
        default_category = POICategory.objects.create(
            icon=poicategory.OTHER,
            color=poicategory.DARK_BLUE,
        )
        POICategoryTranslation = apps.get_model("cms", "POICategoryTranslation")
        POICategoryTranslation.objects.create(
            category=default_category,
            language=default_language,
            name=poicategory.OTHER,
        )

    POI.objects.filter(category=None).update(category=default_category)


class Migration(migrations.Migration):
    """
    Make category selection mandatory for POI
    """

    dependencies = [
        ("cms", "0079_alter_page_mirrored_page"),
    ]

    operations = [
        migrations.RunPython(check_and_update_poicategory, migrations.RunPython.noop),
        migrations.AlterField(
            model_name="poi",
            name="category",
            field=models.ForeignKey(
                on_delete=models.PROTECT,
                related_name="pois",
                to="cms.poicategory",
                verbose_name="category",
            ),
        ),
    ]
