# Data migration: fill ReferralInvitedEmail from existing UserReferralProfile (referred_by is not null)

from django.db import migrations


def backfill_invited_emails(apps, schema_editor):
    UserReferralProfile = apps.get_model('referrals', 'UserReferralProfile')
    ReferralInvitedEmail = apps.get_model('referrals', 'ReferralInvitedEmail')
    for profile in UserReferralProfile.objects.filter(referred_by__isnull=False).select_related('user', 'referred_by'):
        email_lower = profile.user.email.lower().strip()
        if not ReferralInvitedEmail.objects.filter(email=email_lower).exists():
            ReferralInvitedEmail.objects.create(
                email=email_lower,
                referrer=profile.referred_by,
                referred_user=profile.user,
            )


def noop(apps, schema_editor):
    pass


class Migration(migrations.Migration):

    dependencies = [
        ('referrals', '0002_add_referral_antifraud_models'),
    ]

    operations = [
        migrations.RunPython(backfill_invited_emails, noop),
    ]
