# Generated by Django 4.2.20 on 2025-03-12 11:44

from django.db import migrations, models


def fill_referer(apps, schema_editor):
    UserSession = apps.get_model("fingerprint", "UserSession")
    RequestFingerprint = apps.get_model("fingerprint", "RequestFingerprint")

    # fill referer value from the earliest session request fingerprint
    fingerprint_subquery = (
        RequestFingerprint.objects.filter(user_session_id=models.OuterRef("pk"))
        .order_by("created")
        .values_list("referer", flat=True)[:1]
    )

    UserSession.objects.annotate(fp_referer=models.Subquery(fingerprint_subquery)).filter(
        fp_referer__isnull=False
    ).update(referer=models.F("fp_referer"))


class Migration(migrations.Migration):
    dependencies = [
        ("fingerprint", "0005_user_session_utm_fields"),
    ]

    operations = [
        migrations.AddField(
            model_name="usersession",
            name="referer",
            field=models.CharField(blank=True, max_length=2047),
        ),
        migrations.RunPython(fill_referer, migrations.RunPython.noop),
    ]
