# Generated by Django 3.2.14 on 2022-09-06 10:05

from __future__ import annotations

from typing import TYPE_CHECKING

import django.db.models.deletion
from django.db import migrations, models

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

# Color constants for better readable output
WARN = "\x1b[1;33m"
RESET = "\x1b[0;39m"


# pylint: disable=unused-argument
def delete_organizations(apps: Apps, schema_editor: BaseDatabaseSchemaEditor) -> None:
    """
    Delete all existing organizations because they have to be region-specific now

    :param apps: The configuration of installed applications
    :param schema_editor: The database abstraction layer that creates actual SQL code
    """
    Organization = apps.get_model("cms", "Organization")
    if organizations := Organization.objects.all():
        print(
            f"\n    ↳ {WARN}Warning:{RESET} Deleting organizations {organizations!r}",
            end="",
        )
        organizations.delete()


class Migration(migrations.Migration):
    """
    Add region field to organization model
    """

    dependencies = [
        ("cms", "0033_alter_languagetreenode_visible"),
    ]

    operations = [
        migrations.AlterModelOptions(
            name="organization",
            options={
                "default_permissions": ("change", "delete", "view"),
                "default_related_name": "organizations",
                "ordering": ["name"],
                "verbose_name": "organization",
                "verbose_name_plural": "organizations",
            },
        ),
        # Force the deletion function to run immediately so the region field can be added as non-nullable without default
        migrations.RunSQL("SET CONSTRAINTS ALL IMMEDIATE;"),
        migrations.RunPython(delete_organizations, migrations.RunPython.noop),
        migrations.RunSQL("SET CONSTRAINTS ALL DEFERRED;"),
        migrations.AddField(
            model_name="organization",
            name="region",
            field=models.ForeignKey(
                on_delete=django.db.models.deletion.CASCADE,
                related_name="organizations",
                to="cms.region",
                verbose_name="region",
            ),
        ),
    ]
