# Generated by Django 2.0.6 on 2018-08-24 14:21

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


def create_userplans(apps, schema_editor):
    """
    Create UserPlan instances for users that don't have one.

    This function uses the historical model state to avoid issues with
    fields that don't exist yet in the database schema (like updated_at
    which is added in migration 0011).
    """
    User = apps.get_model(settings.AUTH_USER_MODEL)
    Plan = apps.get_model("plans", "Plan")
    UserPlan = apps.get_model("plans", "UserPlan")

    # Get the default plan
    try:
        default_plan = Plan.objects.filter(default=True).first()
    except Plan.DoesNotExist:
        default_plan = None

    if default_plan is None:
        # No default plan exists, skip creating user plans
        return

    # Find users without user plans
    users_without_plans = User.objects.filter(userplan=None)

    # Create user plans for these users
    for user in users_without_plans:
        UserPlan.objects.create(
            user=user,
            plan=default_plan,
            active=False,
            expire=None,
        )


class Migration(migrations.Migration):
    dependencies = [
        ("plans", "0003_make_plans_unique"),
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
    ]

    operations = [
        migrations.RunPython(create_userplans, reverse_code=migrations.RunPython.noop),
    ]
