# Generated by Django 2.1.15 on 2021-08-24 13:26

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

from sentry.utils.query import RangeQuerySetWrapperWithProgressBar


def backfill_visits(apps, schema_editor):
    DiscoverSavedQuery = apps.get_model("sentry", "DiscoverSavedQuery")
    Dashboard = apps.get_model("sentry", "Dashboard")

    for saved_query in RangeQuerySetWrapperWithProgressBar(DiscoverSavedQuery.objects.all()):
        changed = False

        if saved_query.visits is None:
            saved_query.visits = 1
            changed = True

        if saved_query.last_visited is None:
            saved_query.last_visited = timezone.now()
            changed = True

        if changed:
            saved_query.save()

    for dashboard in RangeQuerySetWrapperWithProgressBar(Dashboard.objects.all()):
        changed = False

        if dashboard.visits is None:
            dashboard.visits = 1
            changed = True

        if dashboard.last_visited is None:
            dashboard.last_visited = timezone.now()
            changed = True

        if changed:
            dashboard.save()


class Migration(migrations.Migration):
    # This flag is used to mark that a migration shouldn't be automatically run in
    # production. We set this to True for operations that we think are risky and want
    # someone from ops to run manually and monitor.
    # General advice is that if in doubt, mark your migration as `is_dangerous`.
    # Some things you should always mark as dangerous:
    # - Large data migrations. Typically we want these to be run manually by ops so that
    #   they can be monitored. Since data migrations will now hold a transaction open
    #   this is even more important.
    # - Adding columns to highly active tables, even ones that are NULL.
    is_dangerous = False

    # This flag is used to decide whether to run this migration in a transaction or not.
    # By default we prefer to run in a transaction, but for migrations where you want
    # to `CREATE INDEX CONCURRENTLY` this needs to be set to False. Typically you'll
    # want to create an index concurrently when adding one to an existing table.
    # You'll also usually want to set this to `False` if you're writing a data
    # migration, since we don't want the entire migration to run in one long-running
    # transaction.
    atomic = False

    dependencies = [
        ("sentry", "0226_add_visits"),
    ]

    operations = [
        migrations.RunPython(
            backfill_visits,
            migrations.RunPython.noop,
            hints={"tables": ["sentry_discoversavedquery", "sentry_dashboard"]},
        ),
    ]
