# Generated by Django 2.1.2 on 2018-10-04 13:14

from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion


def initialise_oauth_user_info(apps, schema_editor):
    # We can't import the Person model directly as it may be a newer
    # version than this migration expects. We use the historical version.
    OAuthToken = apps.get_model('blender_id_oauth_client', 'OAuthToken')
    OAuthUserInfo = apps.get_model('blender_id_oauth_client', 'OAuthUserInfo')

    for row in OAuthToken.objects.values('user_id', 'oauth_user_id').distinct():
        user_id = row['user_id']
        oauth_user_id = row['oauth_user_id']
        assert isinstance(user_id, int), f'expected int, not {user_id!r}'
        assert isinstance(oauth_user_id, str), f'expected str, not {oauth_user_id!r}'

        OAuthUserInfo.objects.get_or_create(
            user_id=user_id,
            defaults={'oauth_user_id': oauth_user_id})


def noop(apps, schema_editor):
    # Reverting the data isn't necessary, as the whole table will be dropped anyway.
    pass


class Migration(migrations.Migration):
    dependencies = [
        ('auth', '0009_alter_user_last_name_max_length'),
        ('blender_id_oauth_client', '0001_initial'),
    ]

    operations = [
        migrations.CreateModel(
            name='OAuthUserInfo',
            fields=[
                ('user',
                 models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, primary_key=True,
                                      related_name='oauth_info', serialize=False,
                                      to=settings.AUTH_USER_MODEL)),
                ('oauth_user_id', models.CharField(max_length=255)),
            ],
        ),
        migrations.RunPython(initialise_oauth_user_info, noop),
        migrations.RemoveField(
            model_name='oauthtoken',
            name='provider',
        ),
    ]
