# Generated by Django 2.2.15 on 2020-11-12 13:38

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


def recompute_value_for_new_field(apps, schema_editor):
    VerificationToken = apps.get_model('verification_token', 'VerificationToken')
    expiring_tokens_qs = VerificationToken.objects.filter(expiration_in_minutes__isnull=False)
    expiration_minutes = expiring_tokens_qs.order_by('expiration_in_minutes').values('expiration_in_minutes').distinct(
        ).values_list('expiration_in_minutes', flat=True)

    for minute_number in expiration_minutes:
        expiring_tokens_qs.filter(expiration_in_minutes=minute_number).update(
            expires_at=models.F('created_at') + timedelta(minutes=minute_number)
        )

    assert VerificationToken.objects.filter(expiration_in_minutes__isnull=False, expires_at__isnull=True).count() == 0


class Migration(migrations.Migration):

    dependencies = [
        ('verification_token', '0003_migration'),
    ]

    operations = [
        migrations.AddField(
            model_name='verificationtoken',
            name='expires_at',
            field=models.DateTimeField(blank=True, default=None, null=True),
        ),
        migrations.RunPython(recompute_value_for_new_field),
    ]
