# Generated by Django 4.2.5 on 2023-10-30 13:04

from django.db import migrations


def migrate_message_data_to_new_schema(apps, schema_editor):
    """Migrate the JSON data from the old schema to the new schema.

    Changes:
        - "message" is now "body"
        - "recipient_list" is now "to"
        - "html_message" is now a part of "alternatives", a list of tuples of (content, mimetype)

    Adds:
        - "cc"
        - "bcc"
        - "reply_to"
        - "extra_headers"
        - "alternatives"
    """
    Message = apps.get_model("email_relay", "Message")

    for message in Message.objects.all():
        data = message.data
        if not data:
            continue
        data["body"] = data.pop("message", "")
        data["to"] = data.pop("recipient_list", [])
        data["cc"] = []
        data["bcc"] = []
        data["reply_to"] = []
        data["extra_headers"] = {}
        data["alternatives"] = []
        html_message = data.pop("html_message", None)
        if html_message:
            data["alternatives"].append((html_message, "text/html"))
        message.save()


class Migration(migrations.Migration):
    dependencies = [
        ("email_relay", "0001_initial"),
    ]

    operations = [
        migrations.RunPython(
            migrate_message_data_to_new_schema, migrations.RunPython.noop
        ),
    ]
