# Generated by Django 5.1.7 on 2025-03-22 12:28

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


def forwards(apps, schema_editor):
    # Update the latest snapshot for each bookmark
    Bookmark = apps.get_model("bookmarks", "bookmark")
    BookmarkAsset = apps.get_model("bookmarks", "bookmarkasset")

    latest_snapshots = (
        BookmarkAsset.objects.filter(
            bookmark=OuterRef("pk"), asset_type="snapshot", status="complete"
        )
        .order_by("-date_created")
        .values("id")[:1]
    )
    Bookmark.objects.update(latest_snapshot_id=Subquery(latest_snapshots))


def reverse(apps, schema_editor):
    pass


class Migration(migrations.Migration):

    dependencies = [
        ("bookmarks", "0043_userprofile_collapse_side_panel"),
    ]

    operations = [
        migrations.AddField(
            model_name="bookmark",
            name="latest_snapshot",
            field=models.ForeignKey(
                blank=True,
                null=True,
                on_delete=django.db.models.deletion.SET_NULL,
                related_name="latest_snapshot",
                to="bookmarks.bookmarkasset",
            ),
        ),
        migrations.RunPython(forwards, reverse),
    ]
