# Generated by Django 3.2.15 on 2023-03-30 22:39

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

from ...core.pgutils import chunk_queryset

BATCH_SIZE_LIMIT = 50


def migrate_threads_subscriptions(apps, schema_editor):
    WatchedThread = apps.get_model("misago_notifications", "WatchedThread")
    Subscription = apps.get_model("misago_threads", "Subscription")

    WatchedThread.objects.all().delete()

    timezone_now = timezone.now()
    batch = []
    batch_size = 0

    for subscription in chunk_queryset(Subscription.objects.all()):
        batch.append(
            WatchedThread(
                user_id=subscription.user_id,
                category_id=subscription.category_id,
                thread_id=subscription.thread_id,
                send_emails=subscription.send_email,
                created_at=timezone_now,
                read_at=subscription.last_read_on,
            )
        )
        batch_size += 1

        if batch_size == BATCH_SIZE_LIMIT:
            WatchedThread.objects.bulk_create(batch)
            batch = []
            batch_size = 0

    if batch:
        WatchedThread.objects.bulk_create(batch)


class Migration(migrations.Migration):
    atomic = False
    dependencies = [
        ("misago_notifications", "0001_initial"),
        ("misago_threads", "0001_initial"),
    ]

    operations = [
        migrations.RunPython(migrate_threads_subscriptions, migrations.RunPython.noop),
    ]
