# Generated by Django 4.2.7 on 2023-11-06 01:46

from django.db import migrations, models
from loguru import logger
from tqdm import tqdm


def migrate_relationships(apps, schema_editor):
    User = apps.get_model("users", "User")
    APIdentity = apps.get_model("users", "APIdentity")
    TakaheBlock = apps.get_model("takahe", "Block")
    TakaheFollow = apps.get_model("takahe", "Follow")
    # from takahe.models import Block as TakaheBlock
    # from takahe.models import Follow as TakaheFollow
    # from users.models import APIdentity, User

    logger.info(f"Migrate local user relationship")
    for user in tqdm(User.objects.filter(is_active=True)):
        identity = APIdentity.objects.get(user=user)
        for target in user.local_following.all():
            target_identity = APIdentity.objects.get(user=target)
            identity.follow(target_identity)
        for target in user.local_blocking.all():
            target_identity = APIdentity.objects.get(user=target)
            identity.block(target_identity)
        for target in user.local_muting.all():
            target_identity = APIdentity.objects.get(user=target)
            identity.mute(target_identity)
    logger.info(f"Migrate sync user relationship")
    for user in tqdm(User.objects.filter(is_active=True)):
        user.sync_relationship()
    logger.info(f"Update relationship states")
    TakaheBlock.objects.all().update(state="sent")
    TakaheFollow.objects.all().update(state="accepted")


class Migration(migrations.Migration):
    dependencies = [
        ("users", "0013_init_identity"),
    ]

    operations = [
        migrations.AddField(
            model_name="preference",
            name="mastodon_skip_relationship",
            field=models.BooleanField(default=False),
        ),
        migrations.AddField(
            model_name="preference",
            name="mastodon_skip_userinfo",
            field=models.BooleanField(default=False),
        ),
        migrations.RunPython(migrate_relationships),
    ]
