# Generated by Django 4.2.13 on 2024-07-03 18:01

import django.db.models.deletion
from dateutil.relativedelta import relativedelta
from django.db import migrations, models
from django.utils.timezone import localtime


def create_template_ids_from_slugs(apps, schema_editor):
    DialerMessage = apps.get_model("pymess", "DialerMessage")
    DialerTemplateDisallowedObject = apps.get_model("pymess", "DialerTemplateDisallowedObject")
    DialerTemplate = apps.get_model("pymess", "DialerTemplate")

    EmailTemplate = apps.get_model("pymess", "EmailTemplate")
    EmailMessage = apps.get_model("pymess", "EmailMessage")
    EmailTemplateAttachment = apps.get_model("pymess", "EmailTemplateAttachment")
    EmailTemplateDisallowedObject = apps.get_model("pymess", "EmailTemplateDisallowedObject")

    SMSTemplate = apps.get_model("pymess", "SMSTemplate")
    OutputSMSMessage = apps.get_model("pymess", "OutputSMSMessage")

    PushNotificationTemplate = apps.get_model("pymess", "PushNotificationTemplate")
    PushNotificationMessage = apps.get_model("pymess", "PushNotificationMessage")
    SMSTemplateDisallowedObject = apps.get_model("pymess", "SMSTemplateDisallowedObject")

    def migrate_back_template(template, relation, cutoff=False):
        for obj in template.objects.all():
            query = relation.objects.filter(template_old=obj.slug)
            if cutoff:
                query = query.exclude(created_at__lt=localtime() - relativedelta(years=1))
            query.update(template=obj.id)

    migrate_back_template(DialerTemplate, DialerMessage, cutoff=True)
    migrate_back_template(DialerTemplate, DialerTemplateDisallowedObject)

    migrate_back_template(EmailTemplate, EmailMessage, cutoff=True)
    migrate_back_template(EmailTemplate, EmailTemplateAttachment)
    migrate_back_template(EmailTemplate, EmailTemplateDisallowedObject)

    migrate_back_template(SMSTemplate, OutputSMSMessage, cutoff=True)

    migrate_back_template(PushNotificationTemplate, PushNotificationMessage, cutoff=True)
    migrate_back_template(PushNotificationTemplate, SMSTemplateDisallowedObject)


class Migration(migrations.Migration):

    dependencies = [
        ("pymess", "0029_migration"),
    ]

    operations = [
        # 1. Drop the foreign key constraint.
        migrations.AlterField(
            model_name="dialermessage",
            name="template",
            field=models.SlugField(blank=True, max_length=100, null=True),
        ),
        migrations.AlterField(
            model_name="dialertemplatedisallowedobject",
            name="template",
            field=models.SlugField(blank=True, max_length=100, null=True),
        ),
        migrations.AlterField(
            model_name="emailmessage",
            name="template",
            field=models.SlugField(blank=True, max_length=100, null=True),
        ),
        migrations.AlterField(
            model_name="emailtemplateattachment",
            name="template",
            field=models.SlugField(blank=True, max_length=100, null=True),
        ),
        migrations.AlterField(
            model_name="emailtemplatedisallowedobject",
            name="template",
            field=models.SlugField(blank=True, max_length=100, null=True),
        ),
        migrations.AlterField(
            model_name="outputsmsmessage",
            name="template",
            field=models.SlugField(blank=True, max_length=100, null=True),
        ),
        migrations.AlterField(
            model_name="pushnotificationmessage",
            name="template",
            field=models.SlugField(blank=True, max_length=100, null=True),
        ),
        migrations.AlterField(
            model_name="smstemplatedisallowedobject",
            name="template",
            field=models.SlugField(blank=True, max_length=100, null=True),
        ),
        # 2. Rename 'template' -> 'template_old'
        migrations.RenameField(
            model_name="dialermessage",
            old_name="template",
            new_name="template_old",
        ),
        migrations.RenameField(
            model_name="dialertemplatedisallowedobject",
            old_name="template",
            new_name="template_old",
        ),
        migrations.RenameField(
            model_name="emailmessage",
            old_name="template",
            new_name="template_old",
        ),
        migrations.RenameField(
            model_name="emailtemplateattachment",
            old_name="template",
            new_name="template_old",
        ),
        migrations.RenameField(
            model_name="emailtemplatedisallowedobject",
            old_name="template",
            new_name="template_old",
        ),
        migrations.RenameField(
            model_name="outputsmsmessage",
            old_name="template",
            new_name="template_old",
        ),
        migrations.RenameField(
            model_name="pushnotificationmessage",
            old_name="template",
            new_name="template_old",
        ),
        migrations.RenameField(
            model_name="smstemplatedisallowedobject",
            old_name="template",
            new_name="template_old",
        ),
        # 3. Slug is no longer a primary key.
        migrations.AlterField(
            model_name="dialertemplate",
            name="slug",
            field=models.SlugField(editable=False, max_length=100),
        ),
        migrations.AlterField(
            model_name="emailtemplate",
            name="slug",
            field=models.SlugField(editable=False, max_length=100),
        ),
        migrations.AlterField(
            model_name="pushnotificationtemplate",
            name="slug",
            field=models.SlugField(editable=False, max_length=100),
        ),
        migrations.AlterField(
            model_name="smstemplate",
            name="slug",
            field=models.SlugField(editable=False, max_length=100),
        ),
        # 4. We create a new primary key -> AutoField
        migrations.AddField(
            model_name="dialertemplate",
            name="id",
            field=models.AutoField(auto_created=True, primary_key=True, serialize=False),
            preserve_default=False,
        ),
        migrations.AddField(
            model_name="emailtemplate",
            name="id",
            field=models.AutoField(auto_created=True, primary_key=True, serialize=False),
            preserve_default=False,
        ),
        migrations.AddField(
            model_name="pushnotificationtemplate",
            name="id",
            field=models.AutoField(auto_created=True, primary_key=True, serialize=False),
            preserve_default=False,
        ),
        migrations.AddField(
            model_name="smstemplate",
            name="id",
            field=models.AutoField(auto_created=True, primary_key=True, serialize=False),
            preserve_default=False,
        ),
        # 5. We create a new locale field
        migrations.AddField(
            model_name="dialertemplate",
            name="locale",
            field=models.CharField(blank=True, editable=False, max_length=10, null=True),
        ),
        migrations.AddField(
            model_name="emailtemplate",
            name="locale",
            field=models.CharField(blank=True, editable=False, max_length=10, null=True),
        ),
        migrations.AddField(
            model_name="pushnotificationtemplate",
            name="locale",
            field=models.CharField(blank=True, editable=False, max_length=10, null=True),
        ),
        migrations.AddField(
            model_name="smstemplate",
            name="locale",
            field=models.CharField(blank=True, editable=False, max_length=10, null=True),
        ),
        # 5. slug + locale are unique.
        migrations.AlterUniqueTogether(
            name="dialertemplate",
            unique_together={("slug", "locale")},
        ),
        migrations.AlterUniqueTogether(
            name="emailtemplate",
            unique_together={("slug", "locale")},
        ),
        migrations.AlterUniqueTogether(
            name="pushnotificationtemplate",
            unique_together={("slug", "locale")},
        ),
        migrations.AlterUniqueTogether(
            name="smstemplate",
            unique_together={("slug", "locale")},
        ),
        # 6. We need to create removed `template` fields and return the foreign key constraint.
        migrations.AddField(
            model_name="dialermessage",
            name="template",
            field=models.ForeignKey(
                blank=True,
                null=True,
                on_delete=django.db.models.deletion.SET_NULL,
                related_name="dialer_messages",
                to="pymess.dialertemplate",
            ),
        ),
        migrations.AddField(
            model_name="dialertemplatedisallowedobject",
            name="template",
            field=models.ForeignKey(
                blank=True,
                null=True,
                on_delete=django.db.models.deletion.CASCADE,
                related_name="disallowed_objects",
                to="pymess.dialertemplate",
            ),
        ),
        migrations.AddField(
            model_name="emailmessage",
            name="template",
            field=models.ForeignKey(
                blank=True,
                null=True,
                on_delete=django.db.models.deletion.SET_NULL,
                related_name="email_messages",
                to="pymess.emailtemplate",
            ),
        ),
        migrations.AddField(
            model_name="emailtemplateattachment",
            name="template",
            field=models.ForeignKey(
                blank=True,
                null=True,
                on_delete=django.db.models.deletion.CASCADE,
                related_name="template_attachments",
                to="pymess.emailtemplate",
            ),
        ),
        migrations.AddField(
            model_name="emailtemplatedisallowedobject",
            name="template",
            field=models.ForeignKey(
                blank=True,
                null=True,
                on_delete=django.db.models.deletion.CASCADE,
                related_name="disallowed_objects",
                to="pymess.emailtemplate",
            ),
        ),
        migrations.AddField(
            model_name="outputsmsmessage",
            name="template",
            field=models.ForeignKey(
                blank=True,
                null=True,
                on_delete=django.db.models.deletion.SET_NULL,
                related_name="output_sms_messages",
                to="pymess.smstemplate",
            ),
        ),
        migrations.AddField(
            model_name="pushnotificationmessage",
            name="template",
            field=models.ForeignKey(
                blank=True,
                null=True,
                on_delete=django.db.models.deletion.SET_NULL,
                related_name="push_notifications",
                to="pymess.pushnotificationtemplate",
            ),
        ),
        migrations.AddField(
            model_name="smstemplatedisallowedobject",
            name="template",
            field=models.ForeignKey(
                blank=True,
                null=True,
                on_delete=django.db.models.deletion.CASCADE,
                related_name="disallowed_objects",
                to="pymess.smstemplate",
            ),
        ),
        # 7. We need to update `template` field with newly created primary keys.
        migrations.RunPython(create_template_ids_from_slugs),
        # 8. We can safely remove old `template_old` field.
        migrations.RemoveField(
            model_name="dialertemplatedisallowedobject",
            name="template_old",
        ),
        migrations.RemoveField(
            model_name="emailtemplateattachment",
            name="template_old",
        ),
        migrations.RemoveField(
            model_name="emailtemplatedisallowedobject",
            name="template_old",
        ),
        migrations.RemoveField(
            model_name="smstemplatedisallowedobject",
            name="template_old",
        ),
        migrations.RemoveField(
            model_name="dialermessage",
            name="template_old",
        ),
        migrations.RemoveField(
            model_name="emailmessage",
            name="template_old",
        ),
        migrations.RemoveField(
            model_name="outputsmsmessage",
            name="template_old",
        ),
        migrations.RemoveField(
            model_name="pushnotificationmessage",
            name="template_old",
        ),
        # 9. We made the field template temporarily nullable so that we can migrate values.
        migrations.AlterField(
            model_name="emailtemplateattachment",
            name="template",
            field=models.ForeignKey(
                on_delete=django.db.models.deletion.CASCADE,
                related_name="template_attachments",
                to="pymess.emailtemplate",
            ),
        ),
    ]
