# Generated by Django 3.2.4 on 2021-08-27 17:27

from django.db import migrations, models
import django.db.models.expressions


def normalize_readthrough_dates(app_registry, schema_editor):
    """Find any invalid dates and reset them"""
    db_alias = schema_editor.connection.alias
    app_registry.get_model("bookwyrm", "ReadThrough").objects.using(db_alias).filter(
        start_date__gt=models.F("finish_date")
    ).update(start_date=models.F("finish_date"))


def reverse_func(apps, schema_editor):
    """nothing to do here"""


class Migration(migrations.Migration):

    dependencies = [
        ("bookwyrm", "0085_user_saved_lists"),
    ]

    operations = [
        migrations.RunPython(normalize_readthrough_dates, reverse_func),
        migrations.AlterModelOptions(
            name="readthrough",
            options={"ordering": ("-start_date",)},
        ),
        migrations.AddConstraint(
            model_name="readthrough",
            constraint=models.CheckConstraint(
                check=models.Q(
                    ("finish_date__gte", django.db.models.expressions.F("start_date"))
                ),
                name="chronology",
            ),
        ),
    ]