# Copyright © Michal Čihař <michal@weblate.org>
#
# SPDX-License-Identifier: GPL-3.0-or-later

# Generated by Django 4.0.2 on 2022-03-03 09:33

from secrets import token_hex

from django.db import migrations
from django.utils.text import slugify


def migrate_bots(apps, schema_editor):
    ProjectToken = apps.get_model("trans", "ProjectToken")
    User = apps.get_model("weblate_auth", "User")
    Token = apps.get_model("authtoken", "Token")
    Profile = apps.get_model("accounts", "Profile")
    db_alias = schema_editor.connection.alias

    # Create missing users for ProjectTokens
    for token in ProjectToken.objects.using(db_alias).filter(user=None):
        base_name = name = f"bot-{token.project.slug}-{slugify(token.name)}"
        while User.objects.using(db_alias).filter(username=name).exists():
            name = f"{base_name}-{token_hex(2)}"
        token.user = User.objects.using(db_alias).create(
            username=name,
            full_name=f"{token.name}",
            email=f"noreply+token+{token.pk}@weblate.org",
            is_active=False,
            is_bot=True,
        )
        token.save(update_fields=["user"])

    # Correctly flag bot users
    User.objects.using(db_alias).filter(
        is_active=False, username__startswith="bot-"
    ).update(is_active=True, is_bot=True)

    # Migrate tokens and expiry
    for token in ProjectToken.objects.using(db_alias).select_related("user"):
        user = token.user
        Token.objects.using(db_alias).filter(user=user).delete()
        Token.objects.using(db_alias).create(user=user, key=token.token[:40])
        user.date_expires = token.expires
        user.is_active = True
        user.is_bot = True
        user.full_name = token.name
        user.save(update_fields=["date_expires", "is_bot", "is_active", "full_name"])
        group_obj = token.project.defined_groups.get(name="Administration")
        user.groups.add(group_obj)

    # Add missing profiles
    for user in User.objects.using(db_alias).filter(profile__isnull=True):
        Profile.objects.using(db_alias).create(user=user)


class Migration(migrations.Migration):
    dependencies = [
        ("weblate_auth", "0023_user_is_bot"),
        ("trans", "0144_projecttoken_user"),
        ("authtoken", "0002_auto_20160226_1747"),
    ]

    operations = [
        migrations.RunPython(migrate_bots, migrations.RunPython.noop, elidable=True)
    ]
