# Generated by Django 5.0.14 on 2025-11-02 14:51


from django.db import migrations


def populate_affiliate(apps, schema_editor):
    ReferralAction = apps.get_model("django_affiliate_system", "ReferralAction")

    # Update in batches for better performance
    actions = ReferralAction.objects.select_related("referral_link__affiliate")

    for action in actions.iterator(chunk_size=1000):
        if action.referral_link:
            action.affiliate = action.referral_link.affiliate
            action.save(update_fields=["affiliate"])
        else:
            # Handle edge case: actions without referral_link
            print(f"Warning: Action {action.id} has no referral_link")


def reverse_populate(apps, schema_editor):
    # Optional: clear the field if rolling back
    ReferralAction = apps.get_model("django_affiliate_system", "ReferralAction")
    ReferralAction.objects.update(affiliate=None)


class Migration(migrations.Migration):

    dependencies = [
        ("django_affiliate_system", "0003_add_affiliate_to_referralaction"),
    ]

    operations = [
        migrations.RunPython(populate_affiliate, reverse_populate),
    ]
