# Generated by Django 6.0.2 on 2026-02-23

from django.db import migrations, models


def populate_session_created_at(apps, schema_editor):
    """Backfill created_at for existing sessions from earliest item timestamp."""
    Session = apps.get_model("core", "Session")
    SessionItem = apps.get_model("core", "SessionItem")

    sessions = Session.objects.filter(created_at__isnull=True)
    for session in sessions.iterator(chunk_size=500):
        first_timestamp = (
            SessionItem.objects.filter(
                session_id=session.id,
                timestamp__isnull=False,
            )
            .order_by("timestamp")
            .values_list("timestamp", flat=True)
            .first()
        )
        if first_timestamp:
            Session.objects.filter(id=session.id).update(created_at=first_timestamp)


class Migration(migrations.Migration):

    dependencies = [
        ("core", "0032_rename_count_to_user_message_count"),
    ]

    operations = [
        migrations.AddField(
            model_name="session",
            name="created_at",
            field=models.DateTimeField(blank=True, null=True),
        ),
        migrations.RunPython(populate_session_created_at, migrations.RunPython.noop),
    ]
