from django.conf import settings
from django.db import migrations


def backfill(apps, schema_editor):
    """Accounts created before reader profiles existed (e.g. the first admin) get one now."""
    User = apps.get_model(*settings.AUTH_USER_MODEL.split('.'))
    CustomerProfile = apps.get_model('accounts', 'CustomerProfile')
    have = set(CustomerProfile.objects.values_list('user_id', flat=True))
    CustomerProfile.objects.bulk_create(
        [CustomerProfile(user_id=pk) for pk in User.objects.exclude(pk__in=have).values_list('pk', flat=True)])


class Migration(migrations.Migration):
    dependencies = [('accounts', '0004_terms_acceptance')]
    operations = [migrations.RunPython(backfill, migrations.RunPython.noop)]
