# Adds Post.title, Line.author (PROTECT FK to lyric.User), Line.created_at.
# Backfills Post.title from first-line text (truncate 32 + "…" past 35 chars,
# or hardcoded "Notes & recognitions" for KIND_NOTE_UNLOCK), and Line.author
# from Post.owner — except KIND_NOTE_UNLOCK + ownerless rows, which attribute
# to the seeded `adman` User. Depends on lyric/0003_seed_adman so adman
# exists before backfill runs.

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


_NOTE_UNLOCK_TITLE = "Notes & recognitions"


def _truncate_title(text, length=35):
    if len(text) <= length:
        return text
    return text[: length - 3] + "..."


def backfill(apps, schema_editor):
    Post = apps.get_model("billboard", "Post")
    Line = apps.get_model("billboard", "Line")
    User = apps.get_model("lyric", "User")

    adman = User.objects.filter(username="adman").first()

    for post in Post.objects.all():
        if post.kind == "note_unlock":
            post.title = _NOTE_UNLOCK_TITLE
        else:
            first_line = post.lines.order_by("id").first()
            post.title = _truncate_title(first_line.text) if first_line else ""
        post.save(update_fields=["title"])

    now = timezone.now()
    for line in Line.objects.select_related("post").all():
        if line.post.kind == "note_unlock":
            line.author = adman
        elif line.post.owner_id:
            line.author_id = line.post.owner_id
        else:
            line.author = adman
        if line.created_at is None:
            line.created_at = now
        line.save(update_fields=["author", "created_at"])


def reverse_noop(apps, schema_editor):
    pass


class Migration(migrations.Migration):

    dependencies = [
        ("billboard", "0003_post_kind"),
        ("lyric", "0003_seed_adman"),
    ]

    operations = [
        migrations.AddField(
            model_name="post",
            name="title",
            field=models.CharField(default="", max_length=35),
        ),
        migrations.AddField(
            model_name="line",
            name="created_at",
            field=models.DateTimeField(default=timezone.now),
        ),
        migrations.AddField(
            model_name="line",
            name="author",
            field=models.ForeignKey(
                blank=True,
                null=True,
                on_delete=deletion.PROTECT,
                related_name="authored_lines",
                to="lyric.user",
            ),
        ),
        migrations.RunPython(backfill, reverse_noop),
        migrations.AlterField(
            model_name="line",
            name="author",
            field=models.ForeignKey(
                on_delete=deletion.PROTECT,
                related_name="authored_lines",
                to="lyric.user",
            ),
        ),
        migrations.AlterField(
            model_name="line",
            name="created_at",
            field=models.DateTimeField(auto_now_add=True),
        ),
    ]
