# Generated by Django 5.0.6 on 2024-10-16 09:24

from django.db import connection, migrations
from django.db.backends.base.schema import BaseDatabaseSchemaEditor
from django.db.migrations.state import StateApps
from django.db.models import Max, Min
from django.utils.timezone import now as timezone_now
from psycopg2.sql import SQL


def mark_introduce_resolve_topic_modal_as_read(
    apps: StateApps, schema_editor: BaseDatabaseSchemaEditor
) -> None:
    UserActivity = apps.get_model("zerver", "UserActivity")
    max_id = UserActivity.objects.filter(query="update_message_backend").aggregate(
        Max("user_profile_id")
    )["user_profile_id__max"]

    if max_id is None:
        return

    BATCH_SIZE = 10000
    max_id += BATCH_SIZE / 2
    lower_id_bound = UserActivity.objects.filter(query="update_message_backend").aggregate(
        Min("user_profile_id")
    )["user_profile_id__min"]
    timestamp_value = timezone_now()
    while lower_id_bound < max_id:
        upper_id_bound = min(lower_id_bound + BATCH_SIZE - 1, max_id)
        with connection.cursor() as cursor:
            query = SQL("""
                INSERT INTO zerver_onboardingstep (user_id, onboarding_step, timestamp)
                SELECT user_profile_id, 'intro_resolve_topic', %(timestamp_value)s
                FROM zerver_useractivity
                WHERE query = 'update_message_backend'
                AND user_profile_id >= %(lower_id_bound)s AND user_profile_id <= %(upper_id_bound)s
                ON CONFLICT (user_id, onboarding_step) DO NOTHING;
                """)
            cursor.execute(
                query,
                {
                    "timestamp_value": timestamp_value,
                    "lower_id_bound": lower_id_bound,
                    "upper_id_bound": upper_id_bound,
                },
            )

        print(f"Processed {upper_id_bound} / {max_id}")
        lower_id_bound += BATCH_SIZE


def mark_introduce_resolve_topic_modal_as_unread(
    apps: StateApps, schema_editor: BaseDatabaseSchemaEditor
) -> None:
    OnboardingStep = apps.get_model("zerver", "OnboardingStep")

    OnboardingStep.objects.filter(onboarding_step="intro_resolve_topic").delete()


class Migration(migrations.Migration):
    atomic = False
    dependencies = [
        ("zerver", "0609_alter_namedusergroup_can_leave_group"),
    ]

    operations = [
        migrations.RunPython(
            mark_introduce_resolve_topic_modal_as_read,
            reverse_code=mark_introduce_resolve_topic_modal_as_unread,
            elidable=True,
        ),
    ]
