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


def label_existing(apps, schema_editor):
    """Everything already recorded with no IP AND no user-agent came from a
    request-less login — a server-side call, not a person. Those are exactly
    the rows that put false "last signed in" dates against owner accounts."""
    LoginEvent = apps.get_model("accounts", "LoginEvent")
    LoginEvent.objects.filter(ip__isnull=True, user_agent="").update(source="internal")


class Migration(migrations.Migration):

    dependencies = [
        ("accounts", "0003_user_tour_seen_version"),
    ]

    operations = [
        migrations.AddField(
            model_name="loginevent",
            name="source",
            field=models.CharField(
                choices=[
                    ("web", "Browser"),
                    ("internal", "Server-side (not a person)"),
                    ("wordpress", "WordPress (imported history)"),
                ],
                default="web",
                max_length=12,
            ),
        ),
        migrations.AlterField(
            model_name="loginevent",
            name="occurred_at",
            field=models.DateTimeField(default=django.utils.timezone.now),
        ),
        migrations.AddIndex(
            model_name="loginevent",
            index=models.Index(
                fields=["user", "source", "-occurred_at"],
                name="accounts_lo_user_id_src_idx",
            ),
        ),
        migrations.RunPython(label_existing, migrations.RunPython.noop),
    ]
