# Generated by Django 4.2.16 on 2024-10-24 19:46

from django.db import migrations

import djangocms_link.fields


def forward(apps, schema_editor):
    Link = apps.get_model("djangocms_link", "Link")
    links = Link.objects.all()
    for link in links:
        if link.external_link:
            anchor = "#" + link.anchor if link.anchor else ""
            link.link = {"external_link": link.external_link + anchor}
        elif link.internal_link:
            opt = link.internal_link._meta
            link.link = {"internal_link": f"{opt.app_label}.{opt.model_name}:{link.internal_link.pk}"}
            if link.anchor:
                link.link["anchor"] = "#" + link.anchor
        elif link.file_link:
            link.link = {"file_link": str(link.file_link.pk)}
        elif link.phone:
            link.link = {"external_link": f"tel:{link.phone}"}
        elif link.mailto:
            link.link = {"external_link": f"mailto:{link.mailto}"}
        elif link.anchor:
            link.link = {"external_link": "#" + link.anchor}
    Link.objects.bulk_update(links, ["link"])


def backward(apps, schema_editor):
    raise NotImplementedError("Cannot reverse this migration.")


class Migration(migrations.Migration):
    dependencies = [
        ("djangocms_link", "0016_alter_link_cmsplugin_ptr"),
    ]

    operations = [
        migrations.AddField(
            model_name="link",
            name="link",
            field=djangocms_link.fields.LinkField(default={}, verbose_name="Link"),
        ),
        migrations.RunPython(forward, backward, elidable=True),
    ]
