# Generated by Django 3.2.20 on 2023-09-07 13:41

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


class MysqlExemptRemoveConstraint(migrations.RemoveConstraint):
    def database_forwards(self, app_label, schema_editor, from_state, to_state):
        if schema_editor.connection.vendor.startswith("mysql"):
            return
        super().database_forwards(app_label, schema_editor, from_state, to_state)

    def database_backwards(self, app_label, schema_editor, from_state, to_state):
        if schema_editor.connection.vendor.startswith("mysql"):
            return
        super().database_backwards(app_label, schema_editor, from_state, to_state)


class Migration(migrations.Migration):

    dependencies = [
        ("NEMO_billing", "0005_version_2_5_6"),
        ("cap_discount", "0004_shortened_unique_constraints"),
    ]

    def migrate_configuration_core_facilities(apps, schema_editor):
        CAPDiscountConfiguration = apps.get_model("cap_discount", "CAPDiscountConfiguration")

        for config in CAPDiscountConfiguration.objects.all():
            config.core_facilities.add(config.core_facility)

    def migrate_configuration_core_facilities_back(apps, schema_editor):
        CAPDiscountConfiguration = apps.get_model("cap_discount", "CAPDiscountConfiguration")

        for config in CAPDiscountConfiguration.objects.all():
            config.core_facility = config.core_facilities.first()
            config.save(update_fields=["core_facility"])

    operations = [
        migrations.AlterField(
            model_name="capdiscountconfiguration",
            name="core_facility",
            field=models.ForeignKey(
                blank=True,
                help_text="The core facility this CAP applies to",
                null=True,
                on_delete=django.db.models.deletion.CASCADE,
                related_name="cf",
                to="NEMO_billing.corefacility",
            ),
        ),
        # We need to drop the index and constraint temporarily so MySQL is happy removing the unique constraint
        # This solves the Cannot drop index '...': needed in a foreign key constraint
        migrations.AlterField(
            model_name="capdiscountconfiguration",
            name="rate_category",
            field=models.ForeignKey(
                help_text="The rate category this CAP applies to",
                on_delete=django.db.models.deletion.CASCADE,
                to="rates.ratecategory",
                db_index=False,
                db_constraint=False,
            ),
        ),
        migrations.AddField(
            model_name="capdiscountconfiguration",
            name="core_facilities",
            field=models.ManyToManyField(
                blank=True,
                help_text="The core facility(ies) this CAP applies to. If multiple are selected, the CAP is shared between facilities",
                to="NEMO_billing.CoreFacility",
            ),
        ),
        migrations.RemoveConstraint(
            model_name="capdiscountconfiguration",
            name="capdiscountconfiguration_unique_rate_category_facility",
        ),
        MysqlExemptRemoveConstraint(
            model_name="capdiscountconfiguration",
            name="capdiscountconfiguration_unique_rate_category_null_facility",
        ),
        migrations.RunPython(migrate_configuration_core_facilities, migrate_configuration_core_facilities_back),
        migrations.RemoveField(
            model_name="capdiscountconfiguration",
            name="core_facility",
        ),
        # Put back db index and constraint now
        migrations.AlterField(
            model_name="capdiscountconfiguration",
            name="rate_category",
            field=models.ForeignKey(
                help_text="The rate category this CAP applies to",
                on_delete=django.db.models.deletion.CASCADE,
                to="rates.ratecategory",
            ),
        ),
    ]
