# Generated by Django 5.2 on 2026-02-10 00:00

from django.conf import settings
from django.db import migrations, models
from django.db.models import Exists, OuterRef


def backfill_freemium_grandfathered_flags(apps, schema_editor):
    user_app_label, user_model_name = settings.AUTH_USER_MODEL.split(".")
    User = apps.get_model(user_app_label, user_model_name)
    UserBilling = apps.get_model("api", "UserBilling")
    UserFlags = apps.get_model("api", "UserFlags")

    free_billing_exists = UserBilling.objects.filter(
        user_id=OuterRef("pk"),
        subscription="free",
    )
    non_free_billing_exists = UserBilling.objects.filter(
        user_id=OuterRef("pk"),
    ).exclude(subscription="free")

    candidate_users = (
        User.objects.annotate(
            has_free_billing=Exists(free_billing_exists),
            has_non_free_billing=Exists(non_free_billing_exists),
        )
        .filter(has_non_free_billing=False)
    )

    # If djstripe is available, exclude users currently active/trialing on an
    # individual subscription at rollout time.
    try:
        Subscription = apps.get_model("djstripe", "Subscription")
        ContentType = apps.get_model("contenttypes", "ContentType")
        user_content_type = ContentType.objects.get(
            app_label=user_app_label.lower(),
            model=user_model_name.lower(),
        )
        active_user_ids = set(
            Subscription.objects.filter(
                status__in=["active", "trialing"],
                customer__subscriber_content_type_id=user_content_type.id,
            ).values_list("customer__subscriber_id", flat=True)
        )
        if active_user_ids:
            candidate_users = candidate_users.exclude(id__in=active_user_ids)
    except Exception:
        # Keep migration resilient in environments without djstripe/contenttypes.
        pass

    user_ids = list(candidate_users.values_list("id", flat=True))
    if not user_ids:
        return

    UserFlags.objects.filter(user_id__in=user_ids).update(
        is_freemium_grandfathered=True,
    )
    existing_flag_ids = set(
        UserFlags.objects.filter(user_id__in=user_ids).values_list("user_id", flat=True)
    )
    missing_flags = [
        UserFlags(user_id=user_id, is_freemium_grandfathered=True)
        for user_id in user_ids
        if user_id not in existing_flag_ids
    ]
    if missing_flags:
        UserFlags.objects.bulk_create(missing_flags, ignore_conflicts=True)


class Migration(migrations.Migration):
    atomic = False

    dependencies = [
        ("api", "0285_alter_persistentagentcompletion_completion_type"),
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
    ]

    operations = [
        migrations.AddField(
            model_name="userflags",
            name="is_freemium_grandfathered",
            field=models.BooleanField(db_index=True, default=False),
        ),
        migrations.RunPython(
            backfill_freemium_grandfathered_flags,
            reverse_code=migrations.RunPython.noop,
            atomic=False,
        ),
    ]
