from django.db import migrations


def backfill_artist_fk_to_artists(apps, schema_editor):
    Track = apps.get_model("music", "Track")
    TrackArtist = Track.artists.through
    TrackArtist.objects.bulk_create(
        [
            TrackArtist(track_id=r["id"], artist_id=r["artist_fk_id"])
            for r in Track.objects.filter(artist_fk__isnull=False).values("id", "artist_fk_id")
        ],
        ignore_conflicts=True,
    )


class Migration(migrations.Migration):

    dependencies = [
        ("music", "0032_track_artist_fk_and_artists"),
    ]

    operations = [
        migrations.RunPython(
            backfill_artist_fk_to_artists,
            reverse_code=migrations.RunPython.noop,
        ),
    ]
