# Generated by Django 3.2.15 on 2023-01-04 12:36

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

CHUNK_SIZE = 50


def create_settings(apps, _):
    Subject = apps.get_model("misago_oauth2", "Subject")
    User = apps.get_model("misago_users", "User")

    tz_now = timezone.now()
    sso_users = User.objects.filter(sso_id__isnull=False)

    batch = []

    for user in sso_users.iterator(chunk_size=CHUNK_SIZE):
        batch.append(
            Subject(
                sub=str(user.sso_id),
                user=user,
                created_on=tz_now,
                last_used_on=tz_now,
            )
        )

        if len(batch) >= CHUNK_SIZE:
            Subject.objects.bulk_create(batch)
            batch = []

    if batch:
        Subject.objects.bulk_create(batch)


class Migration(migrations.Migration):
    dependencies = [
        ("misago_oauth2", "0001_initial"),
        ("misago_users", "0022_deleteduser"),
    ]

    operations = [migrations.RunPython(create_settings)]
